19

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.

Arun
  • 825
  • 4
  • 14
  • 31

2 Answers2

12

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.

JAVA MODEL

Customer

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

@XmlRootElement(namespace="http://www.example.com")
@XmlType(namespace="http://www.example.com")
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {

    @XmlAttribute
    private int id;

    @XmlElement(namespace="http://www.example.com")
    private String firstName;

    @XmlElement(namespace="http://www.example.com", nillable=true)
    private String lastName;

    @XmlElement(namespace="http://www.example.com")
    private List<PhoneNumber> phoneNumbers = new ArrayList<PhoneNumber>();

}

PhoneNumber

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class PhoneNumber {

    @XmlAttribute
    private String type;

    @XmlValue
    private String number;

}

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

input.xml

<?xml version="1.0" encoding="UTF-8"?>
<ns0:customer xmlns:ns0="http://www.example.com" id="123">
   <ns0:firstName>Jane</ns0:firstName>
   <ns0:lastName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
   <ns0:phoneNumbers type="work">555-1111</ns0:phoneNumbers>
</ns0:customer>

Demo

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 java.io.File;
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"
   } ]
}
bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • @BDoughan : Yes I have seen this in your blog too. But I am getting ClassNotFound Exception on JAXBContextFactory.I have included the jaxb.properties and I put a dependency in pom.xml too. kindly guide me for the correct dependency for that class – Arun Mar 12 '13 at 11:15
  • @user1933756 - Here is a `pom.xml` from an example that I have hosted on GitHub that you can use as a guide: https://github.com/bdoughan/blog20110819/blob/master/pom.xml – bdoughan Mar 12 '13 at 11:27
  • The needed artifact in pom is [eclipselink](https://mvnrepository.com/artifact/org.eclipse.persistence/eclipselink). Also beware that the jaxb.properties files must be in same package as in model but **in resources directory**. – Jose Duarte May 18 '18 at 00:34
0

JsonMarshaller is a Java 1.5 library that allows marshalling and unmarshalling of JSON objects to and from Java objects. This project's goal is above all ease of use, transparency and static type safety. Example

If you have the following Java class:

JAVA:

@Entity
class Book {
@Value
  private String title;
@Value
  private String isbn;
@Value
  private Set<author> authors;
}

@Entity
class Author {
@Value
  private String firstName;
@Value
  private String lastName;
}

and you created a new Book() and populated it with info it could marshal too:

JSON:

{title:   "java",
 isbn:    "122333",
 authors: [{firstName: "Herbert", lastName: "Shield"},
           {firstName: "Pascal",  lastName: "Perez"}]}
Biswajit
  • 2,434
  • 2
  • 28
  • 35