Arun Arun - 1 year ago 80
Java Question

Converting Java Object to Json using Marshaller

Its quite easy to convert a java object to XML by using Marshaller. But I need to convert a java object to JSON by using marshaller alone. I know its good to use gson or Xstream like things., but I need to do using Marshaller.How to achieve it?

Thanks in advance.

Answer Source

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

Below is how this can be done if you are using MOXy as your JAXB provider.



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

public class Customer {

    private int id;

    private String firstName;

    @XmlElement(namespace="", nillable=true)
    private String lastName;

    private List<PhoneNumber> phoneNumbers = new ArrayList<PhoneNumber>();



import javax.xml.bind.annotation.*;

public class PhoneNumber {

    private String type;

    private String number;


To specify MOXy as your JAXB provider you need to include a file called in the same package as your domain model with the following entry (see:




<?xml version="1.0" encoding="UTF-8"?>
<ns0:customer xmlns:ns0="" id="123">
   <ns0:lastName xmlns:xsi="" xsi:nil="true"/>
   <ns0:phoneNumbers type="work">555-1111</ns0:phoneNumbers>


In the demo code below we will use the same JAXB metadata to convert an XML document to Java objects, and then convert those objects back to JSON. With MOXy you can specify JSON output by setting a property on the Marshaller.

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(Customer.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum15357366/input.xml");
        Customer customer = (Customer) unmarshaller.unmarshal(xml)
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
        marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
        marshaller.marshal(customer, System.out);


JSON Output

Below is the JSON output. Note how there are no indicators corresponding to namespaces or XML attributes. Also note the collection of size one was correctly represented as a JSON array (a problem with some other approaches).

   "id" : 123,
   "firstName" : "Jane",
   "lastName" : null,
   "phoneNumbers" : [ {
      "type" : "work",
      "value" : "555-1111"
   } ]