RSS Feed for This PostCurrent Article

Java – Use JSON for Data Transfer

Download Binary and Code

I need to have a lightweight mechanism to pass complex objects between my Java processes. In my previous article, I used XStream or Simple to serialize my object as XML to store the business rule. I could have used the same way to achieve this. However, after some studying, I decided to use JSON since it is more lightweight and the performance is much better.

As quoted from http://json.org/, JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

E.g. for a Person object with name and email, I can pass it around without creating any value object. Since no value object is needed, I do not need to create a jar file to be shared across different processes.

JSONStringer js = new JSONStringer();
// Begin array
js.array();
js.object().key("name").value("jason").
    key("email").value("jason@gmail.com").endObject();
js.object().key("name").value("alex").
    key("email").value("alex@hotmail.com").endObject();
js.endArray();
// end array

// Print out JSON string
System.out.println(js.toString());

// Retrieve the JSONObject
JSONArray ja = new JSONArray(js.toString());
for (int i = 0; i < ja.length(); i++) {
    JSONObject obj = ja.getJSONObject(i);
    System.out.println(obj.getString("name"));
    System.out.println(obj.getString("email"));
}

First I create a JSONStringer which can be used to generate JSON string. Since I need to pass an array of objects, I create the array first. Then I create two Person objects, each one with name and email attributes.

To retrieve the objects, I loop through the array and get the JSONObject. Then I print out the name and email attributes.

The output from the program

[{"name":"jason","email":"jason@gmail.com"},
{"name":"alex","email":"alex@hotmail.com"}]

jason
jason@gmail.com

alex
alex@hotmail.com

This is just a simple example to show JSON's capabilities. You can download the binary, code and samples attached to play with it.

Have fun !!


Trackback URL


RSS Feed for This Post5 Comment(s)

  1. russ | Oct 23, 2007 | Reply

    I must say that after using XML, and then json for transfer between client and server (not Java, but JavaScript) I honestly can’t believe we have AJAX at all. It ought to be AJAJ!

    Nice summary and introduction, keep up the good work.

  2. Pragma | Oct 23, 2007 | Reply

    Nice post. I’ve done some work in this area and would like to contribute the following tidbits:

    While JSON is fantastic at low-overhead data exchange, it does come with some subtle drawbacks. In short, you will more than likely see an impedance-mismatch between JSON and Java since JSON assumes a loosely-typed environment (read: no built-in type info), whereas Java is much less forgiving.

    (using JSONObject from http://www.json.org/java/index.html)

    JSONObject obj = new JSONObject(“{‘foo’:69.0,’bar’:’42’}”);
    int x = obj.get(“foo”); //fail: returns Double
    int y = obj.get(“bar”); //fail: returns String

    Typically this isn’t a problem with explicit serialization. If you plan on using reflection to serialize Java objects, you’ll need to perform some type-checking, and call the appropriate getXYZ() methods rather than blindly get()-ing your data.

    Another small issue is how JSON has no provision for binary data. Much like with XML, the best solution is to base64 encode any such data since JSON typically is delivered as ASCII or UTF-8.

  3. Sean | Oct 23, 2007 | Reply

    YAML works with Ruby, Java, C++, Python, PHP, etc.

    http://yaml.org/

  4. Richard | Nov 9, 2007 | Reply

    Finally a decent example of how to use this API! Saved me a lot of confusion… thanks.

  5. barrier | Nov 18, 2009 | Reply

    Json has some disadvantages over XML
    1. No unicode support
    2. No comment support
    3. data type support is inadequate

3 Trackback(s)

  1. From Transferência de dados em Java com JSON | Tecnologia da Informação - Desenvolvimento e Educação | Oct 23, 2007
  2. From napyfab:blog» Blog Archive » links for 2007-10-24 | Oct 24, 2007
  3. From Use JSON to Transfer Data between .NET and Java Web Services | twit88.com | Oct 26, 2007

Sorry, comments for this entry are closed at this time.