Monday, June 10, 2013

Java/JS/ExtJs: How to convert/serialize Java objects to and from JSON string


Serialize JSON to Java and vice versa
Today I will show you how to convert JSON string to a Java/JS object and vice versa.
Trust me it’s very easy and fast. Also there are few online tools which I would recommend you all while working with JSON. These are really helpful.

  1. JSON online editor : This tool will validate and convert your JSON string to an object like structure. You can add/edit/delete elements from your JSON string quite easily. But this is only for viewing and validating your JSON. Still quite useful.
  2. JSON to POJO generator : Well this tool comes very handy if you want to make Java skeletons of all the classes present inside your JSON string. It will quickly help you create the respective bean classes. You will need this when you have a very large JSON string and you need to create the Java classes having properties matching the JSON string.

With that, let’s start with the actual topic.
How do we serialize JSON string into a Java/JS object and vice versa?

If you need a Java object, import gson-2.2.2.jar into your project.
Gson (also known as Google Gson) is an open source Java library to serialize and deserialize Java objects to (and from) JSON.
  • We will start with serializing Java object to JSON string:
Suppose you have a bean class (having proper getter/setter methods) with following data:

 public class Book {  
  private String name;  
  private String author;  
  private String genre;  
  private Double cost;  
  private Book () {  
  }  
  public Book (String name, String author, String genre, Double cost) {  
   this.name = name;  
   this.author = author;  
   this.genre = genre;  
   this.cost = cost;  
  }  
 @Override  
  public String toString() {  
   return("Name: " + name + ", " + "Author: " + author + ", " + "Genre: " + genre + ", " + "Cost: " + cost);  
  }  


Now let’s create an instance of this class.

 Book wimpyKid = new Book("Diary of a Wimpy Kid", "Jeff Kinney", "Comedy", 200);  

Now to serialize/convert this object into a JSON string you just need to

 Gson gson = new Gson();  
 String wimpyKidJSON = gson.toJson(wimpyKid);  

Print "wimpyKidJSON" and you will get something like this:

 {  
   "name": "Diary of a Wimpy Kid",  
   "author": "Jeff Kinney",  
   "genre": "Comedy",  
   "cost": 200  
 }  

If you are working on Javascript then you need to fire this command:

 JSON.stringify(wimpyKid); //supposing wimpyKid is a Javascript object  

And in ExtJS do the following:

 Ext.encode(wimpyKid); //supposing wimpyKid is a Javascript object  

  • Now let’s do the other way round. Convert/deserialize a JSON string to POJO/JS object:
Now this is interesting, suppose you have only instance of the Book class, then simply execute this:

 Book wimpyKid = new Gson().fromJson(wimpyKidJSON, Book.class); 

This will set all the values from JSON string into the corresponding properties of the Book class.
But in case you have an array of books in the json string, and you want an array of Book classes in return then this can also be done by executing a single command:


List bookList = gson.fromJson(arrayOfBooksJSON, new TypeToken< List <Book >>;()}.getType());


Similary, in case of javascript:

 var bookObj = JSON.parse(wimpyKidJSON) // will give you a javascript object 

And in case of ExtJS:

 var bookObj = Ext.decode(wimpyKidJSON); // will give you a javascript object 

That’s it! Neat, Right?

4 comments:

  1. Just a small comment for security and performance perspective,

    Ext.encode and Ext.decode is not safer methods to use, instead you should use browser's native parse and stringify methods

    to enable native json handling in extjs itself you can set Ext.USE_NATIVE_JSON flag to true before loading your application

    just to check how flawed Ext.encode is execute this script in your code

    Ext.decode("alert('hi')");

    eventhough "alert('hi')" is not valid json it will parse and execute and show alert box in browser (stupid extjs doesn't do data validation before passing it to eval :))

    ReplyDelete
  2. Saket,

    Ext.decode("alert('hi')"); does show the alert box but I tried to parse the same string using the JSON Online Editor and it worked. It created an object with that string!

    But regarding the performance I agree that JSON.parse is the fastest.
    Here is a link to run test on all the available parsers.

    http://jsperf.com/json-parser-vs-eval/5

    ReplyDelete
  3. if you test the same thing in jsonlint.com then it will show that "alert('hi')" is invalid json, and logically it is :)

    ReplyDelete
    Replies
    1. Yes I did that. Missed out on mentioning it!

      Delete