簡體   English   中英

封送處理期間,JAXB為null而不是空字符串

[英]JAXB null instead empty string during marshaling

編組字符串時,如何打印“ null”作為字段值?

示例:error和error_code是字符串,我想使用“ null”作為值,指示在服務器端未發生任何值/錯誤。

{
   "error_code": null,
   "error": null
}

今天,我必須使用EMPTY值,以便“ error_code”或“ error”這些字段通常落入json中,並且如果未將其明確初始化為this.errorCode = StringUtils.EMPTY; 所以今天,我有了下一個json:

{
   "error_code": "",
   "error": ""
}

這就是代碼中的樣子:

@XmlRootElement()
@XmlAccessorType(XmlAccessType.FIELD)
public class Response
{
        @SuppressWarnings("unused")
        private static final Logger log = LoggerFactory.getLogger(Response.class);

        public static final String ERROR_FIELD_NAME = "error";
        public static final String ERROR_CODE_FIELD_NAME = "error_code";

        // @XmlJavaTypeAdapter(CafsResponse.EmptyStringAdapter.class)
        @XmlElement(name = Response.ERROR_CODE_FIELD_NAME)
        private String errorCode;

        // @XmlJavaTypeAdapter(CafsResponse.EmptyStringAdapter.class)
        @XmlElement(name = Response.ERROR_FIELD_NAME)
        private String errorMessage;

    // Empty Constructor
    public Response()
    {
            this.errorCode = StringUtils.EMPTY; // explicit initialization, otherwise error_code will not appear as part of json, how to fix this this ?
            this.errorMessage = StringUtils.EMPTY;
    }

等等...

// Empty Constructor
public Response()
{
        this.errorCode = null; // this variant dosn't work either, and error_code again didn't get to json 
        this.errorMessage = null;
}

看到@XmlJavaTypeAdapter,我認為這可能會幫助我-但沒有:)

而不是空值,我得到“ null”作為字符串。

if (StringUtils.isEmpty(str))
{
   return null;
}
return str;

{
   "error_code": "null", // this is not whta i wanted to get.
   "error": "null"
}

有什么幫助嗎? -問我是否不清楚。

完整清單:

/**
 * Empty string Adapter specifying how we want to represent empty strings
 * (if string is empty - treat it as null during marhsaling)
 * 
 */
@SuppressWarnings("unused")
private static class EmptyStringAdapter extends XmlAdapter<String, String>
{

        @Override
        public String unmarshal(String str) throws Exception
        {
                return str;
        }


        @Override
        public String marshal(String str) throws Exception
        {
                if (StringUtils.isEmpty(str))
                {
                        return null;
                }
                return str;
        }

}

注意:我是EclipseLink JAXB(MOXy)的負責人,並且是JAXB(JSR-222)專家組的成員。

您可以使用MOXy作為JSON提供程序來支持此用例。 下面是一個示例:

響應

MOXy會將標有@XmlElement(nillable=true)屬性編組到您要查找的表示形式中(請參閱: http : //blog.bdoughan.com/2012/04/binding-to-json-xml-handling-null.html )。

package forum11319741;

import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Response {

        public static final String ERROR_FIELD_NAME = "error";
        public static final String ERROR_CODE_FIELD_NAME = "error_code";

        @XmlElement(name = Response.ERROR_CODE_FIELD_NAME, nillable = true)
        private String errorCode;

        @XmlElement(name = Response.ERROR_FIELD_NAME, nillable = true)
        private String errorMessage;

}

jaxb.properties

要將MOXy用作JAXB提供程序,您需要在與域模型相同的程序包中包含一個名為jaxb.properties的文件,並帶有以下條目(請參閱: http : //blog.bdoughan.com/2011/05/specifying-eclipselink- moxy-as-your.html ):

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

演示版

package forum11319741;

import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Response.class);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty("eclipselink.media-type", "application/json");
        marshaller.setProperty("eclipselink.json.include-root", false);

        Response response = new Response();
        marshaller.marshal(response, System.out);
    }

}

輸出量

{
   "error_code" : null,
   "error" : null
}

MOXy和JAX-RS

您可以使用MOXyJsonProvider類在JAX-RS應用程序中將MOXy用作JSON提供程序(請參閱: http ://blog.bdoughan.com/2012/05/moxy-as-your-jax-rs-json-provider 。 html )。

package org.example;

import java.util.*;
import javax.ws.rs.core.Application;
import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider;

public class CustomerApplication  extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        HashSet<Class<?>> set = new HashSet<Class<?>>(2);
        set.add(MOXyJsonProvider.class);
        set.add(CustomerService.class);
        return set;
    }

}

欲獲得更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM