Thursday, November 21, 2013

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.
share|improve this question

2 Answers

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"?>
 xmlns:ns0="" id="123">
xmlns:xsi="" xsi:nil="true"/> type="work">555-1111
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"
   } ]
share|improve this answer
@BDoughan : Yes I have seen this in your blog too. But I am getting ClassNotFound Exception on JAXBContextFactory.I have included the and I put a dependency in pom.xml too. kindly guide me for the correct dependency for that class –  Tom Mar 12 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: –  Blaise Doughan Mar 12 at 11:27
Thanks a ton Doughan :) works great!!! –  Tom Mar 12 at 11:56


oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses

oakleyses said...

mac cosmetics, mont blanc, marc jacobs, canada goose outlet, nike huarache, vans shoes, soccer jerseys, hollister, giuseppe zanotti, beats by dre, abercrombie and fitch, longchamp, insanity workout, celine handbags, bottega veneta, ghd, nfl jerseys, north face outlet, chi flat iron, ugg boots, birkin bag, ugg australia, canada goose, herve leger, ugg pas cher, rolex watches, valentino shoes, canada goose uk, canada goose, ferragamo shoes, canada goose, ugg boots, uggs outlet, north face jackets, soccer shoes, asics running shoes, new balance shoes, p90x, lululemon outlet, canada goose jackets, mcm handbags, instyler, babyliss pro, ugg, wedding dresses, jimmy choo outlet, reebok outlet, nike roshe run

oakleyses said...

parajumpers, karen millen, air max, converse, pandora charms, moncler, louboutin, moncler, links of london, lancel, juicy couture outlet, oakley, hollister, pandora charms, supra shoes, thomas sabo, canada goose, gucci, wedding dresses, timberland boots, swarovski crystal, air max, coach outlet store online, moncler, ray ban, canada goose, moncler, ugg, louis vuitton, swarovski, hollister, montre homme, moncler, hollister clothing store, ralph lauren, rolex watches, moncler outlet, moncler, iphone 6 cases, baseball bats, juicy couture outlet, toms shoes, vans, pandora jewelry, ugg, converse shoes

Anna said...

Great and Useful Article.

Online Java Course

Java Online Training

Java Course Online

Best Recommended books for Spring framework

Java Interview Questions

Java Training Institutes in Chennai

Java Training in Chennai

J2EE Training in Chennai

java j2ee training institutes in chennai

Java Course in Chennai

mary Brown said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java EE Online Training from India. or learn thru Java EE Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.