Json and flexjson on exchanging abstract object data

August 7, 2011 by · 1 Comment
Filed under: java 

JSON is a lightweight text-based open standard designed for human-readable data interchange.  It is widely used in java applications as a replacement of XML. Many times we need to convert java object to json text and vice versa.

You can use Gson to convert java object to JSON format, and convert JSON into java object. And you can export your interface by JSON RPC using jsonrpc4j or json-rpc.

public class Employee
{
    private String name;
    private int salary;
    private String dateOfBirth;

    public static void main(String[] args)
    {
        Employee emp = new Employee();
        emp.setName("david");
        emp.setDateOfBirth("20080801");

        Gson gson = new Gson();
        String jsonString = gson.toJson(emp, Employee.class);
        System.out.println(jsonString);
    }
}

The output would be:

{“name”:”david”,”salary”:0,”dateOfBirth”:”20080801″}

Now you can deserialize the jsonString to an Employee object.

   Employee employee = gson.fromJson(jsonString, Employee.class);
   System.out.println(employee.getName());

The problem with Gson is that it loses the type information on serialization, and you need to provide type information explicitly on deserialization like the above example.

How to serialize and deserialize with automatic type recognization?

Flex Json is the answer. FlexJson would add a “class” attribute in the serialized json string to represent the full qualified class name. Thus you can exchange interface/abstract object by json format. Here’s an example.

        JSONSerializer serializer = new JSONSerializer();
        String empString = serializer.serialize(emp);
        System.out.println(empString);

        JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>();

        Employee eee = (Employee) deserializer.deserialize(empString);
        //System.out.println(eee);

The output would be like this:

{“class“:”com.beyondlinux.demo.bean.Employee”,”dateOfBirth”:”20080801″,”name”:”david”,”salary”:0}

Reference List:

http://en.wikipedia.org/wiki/JSON-RPC

http://code.google.com/p/jsonrpc4j/

http://code.google.com/p/json-rpc/

http://flexjson.sourceforge.net/

Digg This
Reddit This
Stumble Now!
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)