Enumerated XML List in JSON Array via Jettison and JAXB

I use JAXB to marshal an annotated XML object in the form:

<channels> <channel>Test A</channel> <channel>Test B</channel> </channels> 

I want to use JSON instead of JAXB (ala http://blog.bdoughan.com/2011/04/jaxb-and-json-via-jettison.html ), but it marshals something like the following:

  "channels" : { "channel" : [ "Test A", "Test B" ] }, 

Indeed, I want him to marshal the following form:

  "channels" : { {"Test A"}, {"Test B"} }, 

How can i do this? Is this right to do?

+6
source share
2 answers

Note. I am EclipseLink JAXB (MOXy) and a member of the JAXB 2 group (JSR-222) .

The following is an example of how you can support this use case using JSON binding in EclipseLink JAXB (MOXy).

Java Model (Root)

The following is the Java model that I will use for this example.

 import java.util.*; import javax.xml.bind.annotation.*; @XmlRootElement public class Root { private List<String> channels = new ArrayList<String>(); @XmlElementWrapper @XmlElement(name="channel") public List<String> getChannels() { return channels; } } 

Specify MOXy as the JAXB Provider (jaxb.properties)

To specify MOXy as the JAXB provider, you need to include a file named jaxb.properties in the same package as your domain model, with the following entry (see :):

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

Demo code

In the demo code below, we will output the same instance for both XML and JSON.

 import javax.xml.bind.*; import org.eclipse.persistence.jaxb.MarshallerProperties; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Root.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Root root = new Root(); root.getChannels().add("Test A"); root.getChannels().add("Test B"); // Output XML marshaller.marshal(root, System.out); // Output JSON marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json"); marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false); marshaller.setProperty(MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); marshaller.marshal(root, System.out); } } 

Output

The following is the result of running the demo code:

 <?xml version="1.0" encoding="UTF-8"?> <root> <channels> <channel>Test A</channel> <channel>Test B</channel> </channels> </root> 
 { "channels" : [ "Test A", "Test B" ] } 

Additional Information

+4
source

The easiest way is probably converting your JAXB model to an adapted JSON model.

You would do:

  • create an instance of a jaxb model
  • convert it to a json model
  • Marshal JSON Models

Depending on how you instantiate your JAXB model, you may need to directly create a JSON model.

0
source

Source: https://habr.com/ru/post/945276/


All Articles