October 31, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Top 7 Open-Source JSON-Binding Providers Available Today

  • April 4, 2014
  • By Constantin Marian Alin
  • Send Email »
  • More Articles »

Introduction (Business Case)

            JSON, acronym for JavaScript Object Notation, is a lightweight data-interchange format, an alternative to XML, but smaller, faster and easier to parse. Because JSON uses the JavaScript syntax for describing data objects, it is language and platform independent and many parsers and libraries have been developed along the years. In this article, we will play with seven Java JSON libraries; basically, we will try to convert Java objects to JSON format and save it to a file and backwards, reading a JSON file and converting it back to an object. To make this a little more interesting, we will measure the time for each process and see which Java JSON library is faster.

Using the Jackson Library

We will first start with Jackson. Jackson is a “multi-purpose Java library for processing JSON who aims to be the best possible combination of fast, correct, lightweight and ergonomic for developers”. In addition to this, a good thing about Jackson is that it offers three methods for processing JSON format, each of them having it’s pros and cons:

1. Streaming API or incremental parsing/generation: reads and writes JSON content as discrete events

2. Tree model: provides a mutable in-memory tree representation of a JSON document

3. Data binding: converts JSON to and from POJO’s

Since we are interested in converting Java object to and from JSON, we will focus on the third method. Before we can do this, we need to download Jackson. Jackson core functionalities use three libraries, jackson-core-2.3.1, jackson-databind-2.3.1 and jackson-annotations-2.3.1; all three can be downloaded from the Maven repository, under the core section: http://repo1.maven.org/maven2/com/fasterxml/jackson/ .

Now that we have included the necessary libraries, let’s do some work. In order to obtain a JSON complex object from Java POJO’s, we will use the below classes to construct an object of objects. The same POJO’s are used with all of the JSON-binding libraries mentioned in this article:

public class JsonThirdObject {
 
          private int age = 81;
          private String name = "Michael Caine";
          private List<String> messages;
 
          public JsonThirdObject() {
            this.messages = new ArrayList<String>() {
                    {
                              add("You wouldn't hit a man with no trousers..");
                              add("At this point, I'd set you up with a..");
                              add("You know, your bobby dangler, giggle stick,..");
                              }
                    };
          }
          // Getter and setter
}
 
public class JsonSecondObject {
 
          private int age = 83;
          private String name = "Clint Eastwood";
          private JsonThirdObject jsnTO = new JsonThirdObject();
          private List<String> messages;
 
          public JsonSecondObject() {
            this.messages = new ArrayList<String>() {
                    {
                              add("This is the AK-47 assault..");
                              add("Are you feeling lucky..");
                              add("When a naked man's chasing a..");
                              }
                    };
          }
          // Getter and setter
}
 
public class JsonFirstObject {
 
          private int age = 76;
          private String name = "Morgan Freeman";
          private JsonSecondObject jsnSO = new JsonSecondObject();
          private List<String> messages;
 
          public JsonFirstObject() {
            this.messages = new ArrayList<String>() {
                    {
                              add("I once heard a wise man say..");
                              add("Well, what is it today? More..");
                              add("Bruce... I'm God. Circumstances have..");
                              }
                    };
          }
          // Getter and setter
}
 
public class Json {
 
          private int age = 52;
          private String name = "Jim Carrey";
          private JsonFirstObject jsnFO = new JsonFirstObject();
          private List<String> messages;
 
          public Json() {
            this.messages = new ArrayList<String>() {
                    {
                              add("Hey, maybe I will give you..");
                              add("Excuse me, I'd like to..");
                              add("Brain freeze. Alrighty Then I just..");
                              }
                    };
          }
          // Getter and setter
}

The above POJO’s will result in a JSON format file that will look something like this one:

{
   "age":52,
   "name":"Jim Carrey",
   "jsnFO":{
      "age":76,
      "name":"Morgan Freeman",
      "jsnSO":{
         "age":83,
         "name":"Clint Eastwood",
         "jsnTO":{
            "age":81,
            "name":"Michael Caine",
            "messages":[
               "You wouldn't hit a man..",
               "At this point, I'd set you..",
               "You know, your bobby dangler.."
            ]
         },
         "messages":[
            "This is the AK-47 assault..",
            "Are you feeling lucky..",
            "When a naked man's chasing a.."
         ]
      },
      "messages":[
         "I once heard a wise man..",
         "Well, what is it today? More..",
         "Bruce... I'm God. Circumstances have.."
      ]
   },
   "messages":[
      "Hey, maybe I will give you a call..",
      "Excuse me, I'd like to ask you a few..",
      "Brain freeze. Alrighty Then I just heard.."
   ]
}

Now, let us see how we can convert the POJO’s to JSON and write it to a file. Jackson uses an ObjectMapper for providing data binding functionality and this is one of the first thing we need.

Json jsonObj = new Json();
ObjectMapper mapper = new ObjectMapper();

Then, we will use this ObjectMapper to write the values directly to a file:

System.out.println("Convert Java object to JSON format and save to file");
try {
          mapper.writeValue(new File("c:\\jackson.json"), jsonObj);
} catch (JsonGenerationException e) {
} catch (JsonMappingException e) {
} catch (IOException e) {
}

This looks great! Now we have the JSON file. But, how about reading it back to POJO’s? Well, we can use this:

System.out.println("Read JSON from file, convert JSON back to object");
try {
          jsonObj = mapper.readValue(new File("c:\\jackson.json"), Json.class);
} catch (JsonGenerationException e) {
} catch (JsonMappingException e) {
} catch (IOException e) {
}

It seems that with Jackson, we can convert Java objects to JSON format and save it to a file and backwards with just two lines in a try-catch. It looks great, but is it fast? How fast? We will find out later in this article.

Using the Google-Gson Library

The second Java JSON binding library we will discuss is Gson, or if you prefer the full name, the google-gson library. Gson is a Java library capable of converting Java objects into their JSON representation and JSON strings to an equivalent Java object without the need for placing Java annotations in your classes. The best things about Gson are:

  • Provides simple toJson() and fromJson methods to convert Java objects to JSON and vice-versa
  • Alow pre-existing unmodifiable objects to be converted to and from JSON
  • It has extensive support of Java Generics
  • Allow custom representation for objects
  • Support for arbitrarily complex objects

Gson needs only one .jar, the gson-2.2.4.jar, which is located at http://code.google.com/p/google-gson/downloads/list. Going further, to write a Java object to a JSON file, we first need an instance of Gson. Remember that the POJO’s are the same POJO’s used with Jackson.

          Json jsonObj = new Json();
		  Gson gson = new Gson();

          System.out.println("Convert Java object to JSON format and save to file");
		  try (FileWriter writer = new FileWriter("c:\\gson.json")) {
                    writer.write(gson.toJson(jsonObj));
          } catch (IOException e) {
          }

To read it back to Java object, we can use this:

               System.out.println("Read JSON from file, convert JSON string back to object");
                    try (BufferedReader reader = new BufferedReader(new FileReader("c:\\gson.json"))) {
                          jsonObj = gson.fromJson(reader, Json.class);
                    } catch (FileNotFoundException e) {
                    } catch (IOException e) {
                    }

That is all we need to do. Now we can use the jsonObj in further operations. Moreover, because the Gson instance does not maintain any state while invoking JSON operations, we can reuse the same object for multiple Json serialization and deserialization operations.

Using the JSON-lib Library

JSON-lib is a Java library, based on the work by Douglas Crockford, capable of transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans. JSON-lib is downloadable from http://sourceforge.net/projects/json-lib/files/ and it has the following dependencies:

Now that we have included the necessary libraries, let us write our Java object to file. We haven’t changed the POJO’s; they are the same as shown with the Jackson example:

Json jsonObj = new Json();
JSONObject json;
 
System.out.println("Convert Java object to JSON format and save to file");
try (FileWriter writer = new FileWriter("c:\\json-lib.json")) {
          json = JSONObject.fromObject(jsonObj);
          json.write(writer);
} catch (IOException e) {
}

We are back to less coding! Let us see how we can get the Java object back:

System.out.println("Read JSON from file, convert JSON string back to object");
try (BufferedReader reader = new BufferedReader(new FileReader("c:\\json-lib.json"))) {
          jsonObj = (Json) JSONObject.toBean(JSONObject.fromObject(reader), Json.class);
} catch (IOException ex) {
}

That’s it! A question arises, are those dependencies going to affect performance? We will find out later in this article.

Using the Flexjson Library

Flexjson is a lightweight library for serializing and deserializing Java objects into and from JSON format allowing both deep and shallow copies of objects. The depth to which an object is serialized can be controlled with Flexjson and thus making it similar to lazy-loading, allowing us to extract only the information we need. This is not the case, since we want an entire object to be written to file, but it’s good to know that it can do that.

Flexjson is downloadable from http://sourceforge.net/projects/flexjson/files/ and does not need other libraries to work. The first step in using Flexjson is to have an instance of JSONSerializer class and then use that instance to write the object to file:

Json jsonObj = new Json();
JSONSerializer serializer = new JSONSerializer();

System.out.println("Convert Java object to JSON format and save to file");
try (FileWriter writer = new FileWriter("c:\\flexjson.json")) {
          serializer.deepSerialize(jsonObj, writer);
} catch (IOException e) {
}
 

Going further, to read the file back to an object we can do this:

System.out.println("Read JSON from file, convert JSON string back to object"); try (BufferedReader reader = new BufferedReader(new FileReader("c:\\flexjson.json"))) { jsonObj = new JSONDeserializer<Json>().deserialize(reader); } catch (FileNotFoundException e) { } catch (IOException e) { }

Done! It is simple and effective!

Using the Json-io Library

Another Java library capable of JSON processing is json-io. Json-io has two main classes, a reader and a writer, that eliminates the need for using ObjectInputStream and ObjectOutputStream to serialize Java objects and uses the JSON format instead. Json-io will serialize any Java object graph into JSON, and retain the complete graph semantics and object types. It is downloadable from the Maven Central Repository and does not have other dependencies.

We will use Json-io JsonWriter class in order to write the POJO’s to file:

Json jsonObj = new Json();

System.out.println("Convert Java object to JSON format and save to file");
try (JsonWriter writer = new JsonWriter(new FileOutputStream("c:\\json-io.json"))){
          writer.write(jsonObj);
} catch (IOException e) {
}

To read the JSON file back to POJO’s, we can do this:

System.out.println("Read JSON from file, convert JSON string back to object");
try (JsonReader reader = new JsonReader(new FileInputStream(new File("c:\\json-io.json")))) {
          jsonObj = (Json) reader.readObject();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}

As the documentation says, in most cases, Json-io should be faster than JDK’s ObjectInputStream and ObjectOutputStream serialization. We will see soon how fast is comparing with other JSON binding libraries.

Using the Genson Library

Genson is an extensible, scalable, easy to use open-source Java library capable of converting Java objects to JSON and vice-versa. In addition to this, Genson has full support for generics, support for JSON in JAX-RS implementations, for JAXB annotations and types, and allows serialization and deserialization of maps with complex keys.

It is downloadable from http://code.google.com/p/genson/downloads/list and does not have other dependencies. The first thing we need to do to use Genson is to create an instance of it. Using that instance, we will then write the Java object to file:

Json jsonObj = new Json();
Genson genson = new Genson();
 
System.out.println("Convert Java object to JSON format and save to file");
try (FileWriter writer = new FileWriter("c:\\genson.json")) {
          writer.write(genson.serialize(jsonObj));
} catch (IOException | TransformationException e) {
}

Now that we have the file, reading it back to a Java object can be done like this:

System.out.println("Read JSON from file, convert JSON string back to object");
try (BufferedReader reader = new BufferedReader(new FileReader("c:\\genson.json"))) {
          jsonObj = genson.deserialize(reader, Json.class);
} catch (FileNotFoundException e) {
} catch (IOException | TransformationException e) {
} 

Using the JSONiJ Library

The last Java JSON binding library we will discuss in this article is JSONiJ. JSONiJ is JSON parser, a JPath and Marshaller implementation, capable of converting Java objects into their JSON representation and JSON strings to an equivalent Java object. It is downloadable from https://bitbucket.org/jmarsden/jsonij/downloads and does not have other dependencies.

JSONiJ uses an instance of JSONMarshaler and to write a Java object to a JSON file we can use this:

Json jsonObj = new Json();
 
System.out.println("Convert Java object to JSON format and save to file");
try (FileWriter writer = new FileWriter("c:\\jsonij.json")) {
          writer.write(JSONMarshaler.marshalObject(jsonObj).toJSON());
} catch (IOException | JSONMarshalerException e) {
}

Reading it back is not as simple as writing it because we need to use Java Reflection API to put the values back to our POJO’s:

System.out.println("Read JSON from file, convert JSON string back to object");
try (BufferedReader reader = new BufferedReader(new FileReader("c:\\jsonij.json"))) {
          JSON json = JSON.parse(reader);
 
          // Now we need to parse the JSONObject object and put values back 
          // to our Json object
          for (Field field : jsonObj.getClass().getDeclaredFields()) {
                    try {
                              field.setAccessible(true);
                              field.set(field.getName(), json.get(field.getName()));
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                    }
          }
} catch (FileNotFoundException e) {
} catch (IOException | ParserException e) {
}

It looks a bit tricky and needs more coding than the other libraries presented in this article and we will see in the next section how will affect performance.

Benchmark

Now that we learned how to convert Java objects to JSON format and writing it to files, and backwards, it’s time to see which of the above Java JSON-binding libraries works faster. All the following measures were made on an Intel Core i5 laptop with 2.50GHz, running Windows 7 Ultimate 64-bit SP1 and 4,00GB Single-Channel DDR3 RAM.

The benchmarks were run in the same JVM and before starting to measure performance, each library was warmed up. To limit memory usage impact, an explicit call to the garbage collector was made and the type of JVM was set to –server. The charts represent serialization and deserialization average time of JSON data in milliseconds with 50 iterations and 10 warm-up iteration.

Chart 1

As we can see in the above chart, Flexjson serialize small data faster than the other libraries, and JSON-lib is the slowest library when it comes to serializing small data. Regarding deserialization, Gson is the fastest library, and JSON-lib is still the slowest library.

The next chart represents the total time spent in serializing and deserializing our 287 Kb of data:

Chart 2

This shows us that if we have to serialize and deserialize a small amount of data a lot, the fastest library would be Gson, followed by Genson and Flexjson.

            When it comes to large data, things are not the same. In the below chart we have the results for a 108 Mb of data and as we can see, Flexjson is now the second faster library when it comes to serialization and the first place was taken by Jackson. In deserialization, the slowest library in serializing small data, JSON-lib, is now much faster than the other libraries, followed on the second place by Jackson:

Chart 3
1k = 1000 milliseconds

            The next chart shows us that if we have to serialize and deserialize a large amount of data a lot, you should use Jackson or JSON-lib:

           

Chart 4
1k = 1000 milliseconds

Another important measurement is regarding the .jar size and library dependencies. This can also be important for mobile developers and as we can see below, json-io has the smallest size, followed by Flexjson and JSONiJ:

Chart 5

Conclusion

In this article, we learned seven ways to convert Java objects to JSON format and write it to file and backwards, reading JSON files and save it in Java objects. We have also seen which Java JSON-binding library works faster, which is slower, and in what circumstances. As a conclusion, if you know that you are going to use only a small amount of data in your application and you wish to store or read it to and from JSON format, you should consider using Flexjson or Gson. If you are going to use large amounts of data and wish to store or read it to and from JSON format, you should consider using Jackson or JSON-lib.


Tags: open source, JavaScript, JSON, JavaScript Object Notation




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel