Jay*_*aym 6 json jax-rs jaxb jersey
当接收包含null或""值的JSON sting时,如何让JAXB保留空值.
串:{"id":null,"fname":"John","region":""}
返回对象:
 Person {
    Integer id = 0
    String fname = "John"
    Region regions = 0 }
我希望它返回null而不是0
这是我到目前为止:
@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
    private JAXBContext context;
    private Class<?>[] types = {Person.class};
    public JAXBContextResolver() throws Exception {
        this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), types);
    }
    public JAXBContext getContext(Class<?> objectType) {
        for (Class<?> c : types) {
            if (c.equals(objectType)) {
                return context;
            }
        }
        return null;
    }
}
Person.class是注释的,@XmlRootElement我试过调查杰克逊注释,但没有成功.
注意: 我是EclipseLink JAXB (MOXy) 的负责人,也是JAXB (JSR-222)专家组的成员。
下面是如何使用 MOXy 完成此操作的示例。
人
MOXy 将根据Person需要解组对象,而无需指定任何元数据。要使输出 JSON 包含 null 值,您可以使用注释@XmlElement(nillable=true)(请参阅绑定到 JSON 和 XML - 处理 Null)。
package forum8748537;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Person {
    @XmlElement(nillable=true)
    Integer id;
    @XmlElement(nillable=true)
    String fname;
    @XmlElement(nillable=true)
    Region regions;
}
jaxb.属性
要将 MOXy 指定为您的 JAXB (JSR-222) 提供程序,您需要添加一个jaxb.properties在与您的域类相同的包中调用的文件,其中包含以下条目(请参阅指定 EclipseLink MOXy 作为您的 JAXB 提供程序)。
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
演示
package forum8748537;
import java.io.StringReader;
import java.util.*;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
    public static void main(String[] args) throws Exception {
        Map<String, Object> properties = new HashMap<String, Object>(2);
        properties.put("eclipselink.media-type", "application/json");
        properties.put("eclipselink.json.include-root", false);
        JAXBContext jc = JAXBContext.newInstance(new Class[] {Person.class}, properties);
        StringReader json = new StringReader("{\"id\":null,\"fname\":\"John\",\"region\":\"\"}");
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Person person = unmarshaller.unmarshal(new StreamSource(json), Person.class).getValue();
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(person, System.out);
    }
}
输出
{
   "id" : null,
   "fname" : "John",
   "regions" : null
}
在 JAX-RS 应用程序中使用 MOXy
有关在 JAX-RS 应用程序中使用 MOXy 的示例,请参阅: