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. These properties make JSON an ideal data-interchange language. Couple of things we need to know in order to use JSON, how to read and how to write. 

As an example lets create a simple ajax request that submits using a jQuery simple data and JSON together to the server, where JAVA parses it and returns result in a same JSON format.


Sending JSON with Javascript

First what we need to know is how to create a JSON in javascript and later convert it to String so it can be sent together with the other form data.

<script type="text/javascript">
//create a JSON Object
var jsonObject = [];
jsonObject.push({title: 'Title 1', content: 'Content 1'});
jsonObject.push({title: 'Title 2', content: 'Content 2'});
//lets create a string from the JSON, so it can be sent with the other data
var jsonString = JSON.stringify(jsonObject);

Great now we have JSON as a String. Let’s use a jQuery to submit it to the server.

<script type="text/javascript">
//lets data object to be sent
var postData = 
	pageId : 100,
	pageName: "Test",
	pageData: jsonString
    type: 'POST',
    dataType: "json", //lets specify that we will return data as JSON                  
    url: "url to send data to",
    data: postData,
    success: successFinction,
    error: function() {
    	//handle error here


Parsing JSON with JAVA on the server

While working in JAVA, I found Google-gson library to be very helpful. Here is a small example of how we now handle request from Javascript mentioned above.

//lets assume this is our paramater with the JSON as String - request.getParameter("pageData")
String jsonString = request.getParameter("pageData");
JsonParser parser = new JsonParser();
JsonElement tradeElement = parser.parse(jsonString);
JsonArray json = tradeElement.getAsJsonArray();
//lets create a static class
static class CustomPage {
    private String title;
    private String content;
    private CustomPage(String title, String content) {
      this.title = title;
      this.content = content;
//lets itterate now
Gson gson = new Gson();
Type collectionType = new TypeToken<List<CustomPage>>(){}.getType();
List<CustomPage> jsonNodes = gson.fromJson(json, collectionType);		
Iterator<CustomPage> iterator = jsonNodes.iterator();			
	CustomPage node = (CustomPage) iterator.next();
	System.out.println("Title: " + node.title);
	System.out.println("Content: " + node.content);


Sending JSON back as a response from the server to Javascript client

Now when we finish everything on the server it is time for us to send data back and guess what – we will send it as JSON.

data.put("status", "1");
data.put("message", "success!");
//init Gson
Gson gson = new Gson();
//flush it to the page


Parsing JSON response with Javascript

Almost done…let’s now properly handle JSON response from the server. Going back to our jQuery ajax request, lets create “successFinction()”.

<script type="text/javascript">
function successFinction(json) {
	//if you are using a jQuery, notice we passed this parameter above
	// dataType: "json",
	//so we will get a JSON object right from it
	alert("Message: " + json.message);
	//if you are receiving json as a string you can always parse itlike that
	// var jsonObject = eval('(' + jsonString + ')');

Easy Busy…Enjoy!

Dima Svirid

Software architect, JAVA, Spring, Hibernate, AngularJs, Backbone, MongoDB, Oracle. CTO and Co-Founder of Homeadnet.com

More Posts

Follow Me:

Tagged with:

3 Responses to Parsing JSON objects with JAVA and Gson

  1. Sohail Ali says:

    Best Regards,

  2. Anonymous says:

    there is an error.
    The type List is not generic; it cannot be parameterized with arguments <ProjectHandler.CustomPage>.

    on both of following line.
    List<CustomPage> jsonNodes = gson.fromJson(json, collectionType);.

Leave a Reply