3

I use JAXB and JSONProvider class for generating response to client in my REST services. And I have found one interesting thing. I have the mapping:

@XmlRootElement(name = "fooRoot")
@XmlAccessorType(XmlAccessType.FIELD)
public class WSBar {
     private WSFooTO foos;
//...
}

@XmlRootElement(name = "foos")
@XmlAccessorType(XmlAccessType.FIELD)
public class WSFooTO {
    private WSDateTO one;
    private WSDateTO two;
    private WSDateTO three;
    private WSDateTO four;
//....
}

When I set to the response empty objects, I mean: just new WSDateTO() and new WSFooTO () After the, I recive answer like this:

{"fooRoot":{
    "foos":{
        "one":"",
        "two":"",
        "three":"",
        "four":""
    }
}}

Why does it happen? I expect, that it should be: "one":null, "two":null

Duck
  • 26,924
  • 5
  • 64
  • 92
Andry
  • 655
  • 2
  • 11
  • 22

1 Answers1

2

According to a JAXB tutorial the absence of a value can be expressed in three different ways:

  • the element is omitted
  • with an empty String using @XmlElement(required = true) annotation
  • with the sepcial xsi:nil attribute using @XmlElement(nillable = true) annotation

Answering strictly your question: JAXB does not support translating empty objects to null.

Atticus
  • 1,622
  • 7
  • 32
  • 55
  • Also look at http://stackoverflow.com/questions/858598/jaxb-marshalling-with-null-fields question which also shows a way to translate empty objects. – Atticus Jun 27 '12 at 10:40
  • Thank you! But I think, that it's wrong, when object converts to String. Android client' s JSON parser doesn't work. Because it expects Object, not String. Could you please tel, what should I do in the situation? – Andry Jun 27 '12 at 12:05
  • I don not understand what do you want to do. You asked `Why does it happen?` I pointed out why it happens. This is how the JAXB works. What do you want to do now? Please clarify your question. BTW `String` is also an `Object` so your Android client (about which you should give some info if that is the problem) should work. – Atticus Jun 27 '12 at 13:32
  • To clarify, @Andrew was asking about the Android use case. Atticus, thanks for your response. I don't intend for the objects to be empty and I have verified to the best of my ability that they are not empty. However, they're showing up as empty when I'd expect them to be populated. – Foo Feb 28 '13 at 21:37