We are moved to new domain
Click -> www.ehowtonow.com
Saturday, 12 October 2013

How to convert JSON to Java Object using Jackson


In this Tutorials we are going to see how to convert JSON String to Java object using Jackson data binding.

1. Create project called JSONExample.
2. Create package called com.javatutorialscorner.jackson 
3. Create java class called JacksonPojo under com.javatutorialscorner.jackson
JacksonPojo.java
package com.javatutorialscorner.jackson;

import java.util.List;

public class JacksonPojo {
private int id;
private String name;
private List<String> list;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public List<String> getList() {
return list;
}

public void setList(List<String> list) {
this.list = list;
}

}

4. add jackson-mapper-asl-1.9.13.jar, jackson-core-asl-1.9.13.jar into build path.

5. Now Create java class called JacksonReadExample under com.javatutorialscorner.jackson

JacksonReadExample.java

package com.javatutorialscorner.jackson;

import java.io.File;
import java.io.IOException;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonReadExample {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JacksonPojo pojo = null;
ObjectMapper mapper = null;

mapper = new ObjectMapper();
try {
pojo = mapper.readValue(new File(
"C:\\jtc\\javatutorialscorner.json"), JacksonPojo.class);
System.out.println("ID :" + pojo.getId());
System.out.println("Name :" + pojo.getName());
System.out.println("Mathch :" + pojo.getList());
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

The readValue() method used to read the JSON from file and convert it back to Java Object.

Now run the program see the following output in console.

ID :10

Name :Tendulkar

Mathch :[Test - 198 , ODI - 463 , T20 - 1, IPL - 78]

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: How to convert JSON to Java Object using Jackson Rating: 5 Reviewed By: eHowToNow