I want to marshal null objects as null in the JSON representation. But, right now, Am not seeing the element in the JSON if the object is null.
Example:
@XmlAccessType(FIELD)
@XmlType(name="foo" propOrder={"foo"}
class foo{
@XmlElement
private Integer foo;
private Integer another_foo;
..
getter()
setter()
}
In my code am setting foo element to null.
But the JSON representation does not show the element in the response.
The response looks like this
"foo" :{
"another_foo":something
}
I tried setting xml element attribute nillable true. (@XmlElement(nillable=true)
Which makes the response look like,
"foo" :{
"another_foo" : something
"foo":{nil :true}
}
I want it to be like,
"foo" :{
"another_foo":something
"foo" : null
}
What am doing wrong here?
First things first: JAXB does NOT do JSON. It is an XML API. So you are probably using a framework (my guess: JAX-RS implementation like maybe Jersey)? It is necessary to know which one you are using to give more help.
Assuming this, question is, how is the package using JAXB annotations to guide JSON serialization. Some basically convert objects to XML (either logical structure, or full xml), and then convert to JSON using a convention. This may cause data loss because of differences in data model between XML and JSON.
Now: simple solution for most JAX-RS implementations is to not use JAXB annotation based approach at all, but a JSON-specific serializer, such as Jackson's JacksonJsonProvider (Jackson can actually use JAXB annotations, too). It will by default include null values for properties, although this is configurable in case you want to suppress nulls.
Here is JavaDoc that shows how to use Jackson provider (specify FEATURE_POJO_MAPPING for configuration) with Jersey, if that might help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With