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);
</script>

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
};
 
$.ajax({
    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
    }
});
</script>

 

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();			
while(iterator.hasNext()){
	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.

Map<String, String> data = new HashMap<String, String>();
data.put("status", "1");
data.put("message", "success!");
 
//init Gson
Gson gson = new Gson();
 
//flush it to the page
out.println(gson.toJson(data));

 

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 + ')');
 
}
</script>

Easy Busy…Enjoy!

Dima Svirid

Software architect. Ajax/Javascript, HTML5, Android, iPhone/iPad, JAVA, PHP, Cold Fusion, SQL, Air, Flash, Open source software, Frameworks

More Posts

Follow Me:

Tagged with:
 

3 Responses to Parsing JSON objects with JAVA and Gson

  1. Sohail Ali says:

    I’ve gone through your all postings, awesome piece of work. The words are catchy and speech is attractive. I really appreciate your efforts.
    Please allow me to write for you in very low rates, I will not let you down or disappoint you at any cost. Hoping for positive response from you.
    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.
    Type collectionType = new TypeToken<List<CustomPage>>(){}.getType();.
    List<CustomPage> jsonNodes = gson.fromJson(json, collectionType);.

Leave a Reply