Note. I am EclipseLink JAXB (MOXy) and a member of the JAXB 2 group (JSR-222) .
EclipseLink JAXB (MOXy) provides native support for JSON binding. It will correctly marshal collections of size 1 wrapped in a JSON array. The following is a complete example.
Company
package forum3946102; import java.util.List; import javax.xml.bind.annotation.*; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Company { private int id; private String name; private String description; @XmlElement(name = "industries") private List<Industry> industryList; }
Industry
package forum3946102; import javax.xml.bind.annotation.*; @XmlAccessorType(XmlAccessType.FIELD) public class Industry { private int id; private String name; }
jaxb.properties
To specify MOXy as your JAXB provider, you need to add a file called jaxb.properties in the same package as your domain classes, with the following entry:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Demo
package forum3946102; import java.io.StringReader; import javax.xml.bind.*; import javax.xml.transform.stream.StreamSource; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Company.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); unmarshaller.setProperty("eclipselink.media-type", "application/json"); unmarshaller.setProperty("eclipselink.json.include-root", false); String jsonString = "{\"id\":\"0\",\"industries\":[{\"id\":\"0\",\"name\":\"Technologies\"}],\"name\":\"Google Inc.\"}"; StreamSource jsonSource = new StreamSource(new StringReader(jsonString)); Company company = unmarshaller.unmarshal(jsonSource, Company.class).getValue(); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty("eclipselink.media-type", "application/json"); marshaller.setProperty("eclipselink.json.include-root", false); marshaller.marshal(company, System.out); } }
Output
The following is the result of running the demo code:
{"id" : 0, "name" : "Google Inc.", "industries" : [{"id" : 0, "name" : "Technologies"}]}
Additional Information
source share