Sunday, November 30, 2014

Encode and Decode JSON in Java using json-simple

Create a Maven project and add the following dependency to the project:

<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>

Create plain old java obj, something as simple as follows:

package com.memeanalytics.json_demo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DemoEntity {
 private String name = "";
 private Date createDate=new Date();
 private boolean enabled=false;
 private double value = 0;
 private int count = 0;
 
 public String getName()
 {
  return this.name;
 }
 
 public void setName(String name)
 {
  this.name=name;
 }
 
 public String getCreateDateString()
 {
  SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  return formatter.format(this.createDate);
 }
 
 public void setCreateDateString(String dateString)
 {
  SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  try {
   this.createDate = formatter.parse(dateString);
  } catch (ParseException e) {
   e.printStackTrace();
  }
 }
 
 public boolean isEnabled()
 {
  return this.enabled;
 }
 
 public void setEnabled(boolean enabled)
 {
  this.enabled=enabled;
 }
 
 public int getCount()
 {
  return this.count;
 }
 
 public int setCount(int count)
 {
  return this.count = count;
 }
 
 public double getValue() 
 {
  return this.value;
 }
 
 public void setValue(double value)
 {
  this.value=value;
 }
}

Create a utility class with two methods to encode and decode between JSON and the DemoEntity obj:

package com.memeanalytics.json_demo;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonEncoder {
 public static String encode(DemoEntity obj)
 {
  JSONObject json=new JSONObject();
  
  json.put("name", obj.getName());
  json.put("createDate", obj.getCreateDateString());
  json.put("value", obj.getValue());
  json.put("count", obj.getCount());
  
  return json.toJSONString();
 }
 
 public static DemoEntity decode(String jsonString) 
 {
  JSONParser parser=new JSONParser();
  
  DemoEntity obj=null;
  
  try{
   JSONObject json = (JSONObject)parser.parse(jsonString);
   
   obj=new DemoEntity();
   obj.setName((String)json.get("name"));
   obj.setCreateDateString((String)json.get("createDate"));
   obj.setValue((Double)json.get("value"));
   obj.setCount(Integer.parseInt(json.get("count").toString()));
  }catch(ParseException ex)
  {
   ex.printStackTrace();
  }
  return obj;
 }
}

Now in the main class simply invokes the encode and decode methods to switch between JSON and DemoEntity obj:

package com.memeanalytics.json_demo;

public class App 
{
    public static void main( String[] args )
    {
     DemoEntity obj=new DemoEntity();
     
     obj.setName("obj1");
     obj.setValue(12.5);
     obj.setCount(10);
     
     String jsonString = JsonEncoder.encode(obj);
     System.out.println(jsonString);
     
     DemoEntity obj2  = JsonEncoder.decode(jsonString);
     
     if(obj2 != null)
     {
      System.out.println("name : " + obj2.getName());
      System.out.println("created date : " + obj2.getCreateDateString());
      System.out.println("value : "+obj2.getValue());
      System.out.println("count : "+obj2.getCount());
     }
    }
}

Two points to note:

1. for Date() object, i will be safer to convert it to String before put it into a JSONObject during serialization, and vice versa in deserialization.
2. for Integer object, it will be safer to covert the the item returned by JSONObject.get() to a String then parse it to integer during deserialization (as JSONObject.get() usually will return a Long object instead of an Integer object).

Below is the link to the complete source codes:

https://dl.dropboxusercontent.com/u/113201788/storm/json-demo.zip

No comments:

Post a Comment