在编组期间,JAXB为null而是空字符串

时间:2012-07-03 21:54:32

标签: java jaxb jersey

在编组字符串时如何打印'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值,我得到“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;
        }

}

1 个答案:

答案 0 :(得分:0)

注意:我是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;
    }

}

了解更多信息