1

I'm using Jersey v1.19 as REST framework.

Below is an Xml-Annotated class for a Response.

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Data {
   private boolean hasErrors; // always appears because primitive
   private List<String> remainingJobs;    
   // getter and setter
}

The problem here is that when remainingJobs is null or empty, then it is not included in the JSON response! Example of the response: {"hasErrors": false}

I would like to make it appear in the JSON response that's all. Example of the response I would like to see: {"hasErrors": false, "remainingJobs": null} or "null"

However, I found out that if I annotate this data member as

@XmlElementWrapper(name = "remainingJobs")
@XmlElement(name = "remainingJob")
private List<String> remainingJobs;

Then it shows the null. However, the response will be verbose and not pretty when there are actual data. Example:

 {"remainingJobs": {"remainingJob": ["J22", "K01"]}, "hasErrors": false}

What I would like:

 {"remainingJobs": ["J22", "K01"], "hasErrors": false}

Another issue is that when remainingJobs is empty (NOT null) then it is showing as null!!

  • Possible duplicate of http://stackoverflow.com/questions/18983687/jaxb-marshaller-does-not-have-elements-whos-value-is-null – Sampada Jul 13 '16 at 07:05
  • @Sampada I just tried the solution of that question and no it didn't work for me. Seems like a Jersey problem rather than JAXB Marshaller problem –  Jul 13 '16 at 07:16
  • 1
    try using Jackson or Gson for java-json mapping. jaxb is primarily for XML-java – Sampada Jul 13 '16 at 07:20
  • If you use Jackson you can add @JsonSerialize(include=JsonSerialize.Inclusion.ALWAYS) for Data entity to achive this. Or you can set serialization inclusion to object mapper for entire application. mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.ALWAYS) – kartheek vanapalli Jul 13 '16 at 08:47
  • @kartheekvanapalli I did that and it fixed the issue but created another! Now all the fields show! but I don't want that! I want it only for this field! –  Jul 13 '16 at 10:26
  • @rz3r0 Check this link http://stackoverflow.com/questions/12046786/jackson-json-custom-serialization-for-certain-fields to do field level serialization – kartheek vanapalli Jul 13 '16 at 13:45

0 Answers0