Json and flexjson on exchanging abstract object data

August 7, 2011 by
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();

        Gson gson = new Gson();
        String jsonString = gson.toJson(emp, Employee.class);

The output would be:


Now you can deserialize the jsonString to an Employee object.

   Employee employee = gson.fromJson(jsonString, Employee.class);

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);

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

        Employee eee = (Employee) deserializer.deserialize(empString);

The output would be like this:


Reference List:





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)


One Comment on Json and flexjson on exchanging abstract object data

  1. Charlie Hubbard on Tue, 9th Aug 2011 2:31 am
  2. Actually that’s just default behavior for flexjson. If you excluded the class property using .exclude(“*.class”) you could still deserialize the object back into it’s concrete classes. Typically, you’ll have to add some type identifier to the JSON output to know, but you can choose at deserialization time what class should be instantiated without the class property. But, it’s discussed at length on http://flexjson.sourceforge.net/ under the section “Polymorphism, Subclasses, and Interfaces.”