![]() |
| Serialize JSON to Java 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.
- 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.
- 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:
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:
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?
