Google

Aug 5, 2014

Java and JSON tutorial converting JSON to object and vice versa with Jackson library

Q. What is JSON and when to favor it over XML?
A. JSON (JavaScript Object Notation) is a lightweight, text-based, language-netral like XML, but less verbose than XML data exchange format. JSOJ is used in Web services to exchange data between client and server. Client makes ajax requests to get snippets of data in JSON format from the server via RESTful web service calls. JSON is easy for humans and machines to read and write. JSON can be represented as objects and arrays.

XML

<Employee>
   <name type="first">Peter</name>
   <age>25</age>
</Employee>


JSON employee object:

{ 
  "name":"Peter", 
  "nameType":"first", 
  "age":"25"
}


JSON with Name as a separate object

{ 
  "name": {
     "name":"Peter",
  "type":"first"
  }
  "age":"25"
}


JSON Array:

{"employees":[
    {"name":"Peter", nameType="first", "age":"25"}, 
    {"name":"John", nameType="first", "age":"52"},
    {"name":"Simon", nameType="first", "age":"34"}
]}



Jackson library is one of the popular libraries for converting JSON to Java object and vice versa. Here is a simple step by step example.

Step 1: You need to have jackson-core-asl-xxx.jar and jackson-mapper-asl-xxx.jar files in the classpath.

 <dependencies>
 <dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-mapper-asl</artifactId>
  <version>1.9.5</version>
 </dependency>
 <dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-core-asl</artifactId>
  <version>1.9.5</version>
 </dependency>
  </dependencies>


Step 2: The Employee Java object.

package com.json;

public class Employee {

 private String name;
 private String type;
 private int age;

 public String getName() {
  return name;
 }

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

 public String getType() {
  return type;
 }

 public void setType(String type) {
  this.type = type;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 @Override
 public String toString() {
  StringBuilder sb = new StringBuilder();
  sb.append("name=" + this.name);
  if (type != null) {
   sb.append("\ntype=" + type);
  }
  sb.append("\n");
  sb.append("age=" + age);
  return sb.toString();
 }
}


Step 3: Jackson in action.

package com.json;

import java.io.IOException;

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

public class JsonExample {
 
 public static void main(String[] args) {
  String json = "{ \"name\":\"Peter\", \"type\":\"first\", \"age\":\"25\"}";
  
  ObjectMapper mapper = new ObjectMapper();
  
  try {
   //convert JSON to Java object
   Employee readValue = mapper.readValue(json.getBytes(), Employee.class);
   System.out.println("object:" + readValue);
   
   //convert Java object to JSON
   mapper.writeValue(System.out, readValue);
   
  } catch (IOException  e) {
   e.printStackTrace();
  } 
 }
}

Output:

object:name=Peter
type=first
age=25
{"name":"Peter","type":"first","age":25}


Converting Java Map to JSON and vice versa using Jackson

package com.json;

import java.io.IOException;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

public class JsonExample {

 public static void main(String[] args) {
  String json = "{ \"name\":\"Peter\", \"type\":\"first\", \"age\":\"25\"}";

  ObjectMapper mapper = new ObjectMapper();

  try {
   // convert JSON to Map
   Map mapObject = mapper.readValue(json.getBytes(), 
     new TypeReference>() {
   });

   System.out.println("object:" + mapObject);

   // convert Map to JSON
   mapper.writeValue(System.out, mapObject);

  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}


Output:

object:{name=Peter, type=first, age=25}
{"name":"Peter","type":"first","age":"25"}

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home