merce handig
merce handig

Reputation: 81

jaxb list with one element

I produce JSON with a List<> member inside. It is marshalled OK.

However, my consuming (third-)party complains about a missing []-pair, when the list has only one element. What I produce is like:

"mylist":{"id":104,"name":"Only one found"} // produced

while my consumer expects:

"mylist":[{"id":104,"name":"Only one found"}] // expected by third party

Is my implementation producing incorrect JSON?

Upvotes: 3

Views: 2322

Answers (1)

bdoughan
bdoughan

Reputation: 149047

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

The JAXB (JSR-222) specification does not cover JSON-binding. The behaviour you are seeing is most likely due to a JAXB implementation being used with a library like Jettison. Jettison converts StAX events to/from JSON and can only detect a list when an element occurs more than once (see: http://blog.bdoughan.com/2011/04/jaxb-and-json-via-jettison.html). EclipseLink JAXB offers native JSON binding and can correctly represent arrays of size 1.

JAVA MODEL

Foo

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {

    private List<Bar> mylist;

}

Bar

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Bar {

    private int id;
    private String name;

}

jaxb.properties

To specify MOXy as your JAXB provider you need to include a file called jaxb.properties in the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html):

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

DEMO CODE

Demo

import java.util.*;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> properties = new HashMap<String, Object>(2);
        properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
        properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
        JAXBContext jc = JAXBContext.newInstance(new Class[] {Foo.class}, properties);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StreamSource json = new StreamSource("src/forum15404528/input.json");
        Foo foo = unmarshaller.unmarshal(json, Foo.class).getValue();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(foo, System.out);
    }

}

input.json/Output

We see that the mylist is correctly represented as a JSON array.

{
   "mylist" : [ {
      "id" : 104,
      "name" : "Only one found"
   } ]
}

ADDITIONAL INFORMATION

Upvotes: 3

Related Questions