Convert Java Object To / From JSON, EclipseLink MOXy Example

On this EclipseLink MOXy Example explains about converting a java object to JSON string and JSON string to java Object Using EclipseLink MOXy library.

EclipseLink MOXy component enables Java developers to efficiently bind Java classes to XML Schemas. MOXy implements JAXB allowing developers to provide their mapping information through annotations as well as providing support for storing the mappings in XML format. The many advanced mappings enable developers to handle the complex XML structures without having to mirror the schema in their Java class model.

Reference -> www.eclipse.org/eclipselink/moxy.php

Here I am showing an example about How to convert a Java Object to JSON string and vice versa using EclipseLink MOXy.

Required Libraries

You need to download

  1. EclipseLink MOXy

Following jar must be in classpath

  1. eclipselink.jar

Project structure

Convert Java Object To / From JSON, EclipseLink MOXy Example

Student.java

Here I am creating a pojo class, this will be the converted in to JSON string.

package net.javatips;

public class Student {

  
private String firstName="Rockey";
  
private String lastName="Desousa";

  
public String getFirstName() {
     
return firstName;
  
}

  
public void setFirstName(String firstName) {
     
this.firstName = firstName;
  
}

  
public String getLastName() {
     
return lastName;
  
}

  
public void setLastName(String lastName) {
     
this.lastName = lastName;
  
}

  
@Override
  
public String toString() {
     
return "Student [firstName=" + firstName + ", lastName=" + lastName + "]";
  
}
  
}

jaxb.properties

just add the following line into jaxb.properties (see the project structure)

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

For converting Java Student Object to JSON string, you can use following method, Here student.json is a file

Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(student, new File("student.json"));

For converting JSON string to Java Student Object, you can use following method

Unmarshaller unmarshaller = jc.createUnmarshaller();
student = (Student) unmarshaller.unmarshal(new File("student.json"));
1 2 Next





3 Responses to "Convert Java Object To / From JSON, EclipseLink MOXy Example"
  1. Richard 2013-09-04 08:47:49.0
  1. admin 2013-09-05 08:47:49.0
  1. twist 2013-09-06 08:47:49.0

Your email address will not be published. Required fields are marked *