Parsing JSON objects with JAVA and Gson
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
3 Responses to Parsing JSON objects with JAVA and Gson
Leave a Reply Cancel reply
You must be logged in to post a comment.
SEARCH ARTICLES & TUTORIALS
MOST POPULAR TUTORIALS
Generating PDF Documents with Adobe Air Javascript SDK and jQuery
I am not a Flex guy and I don't think I will ever be. While searching [...]
Search Engine Optimization - Do It Yourself!
This is Part 1 of "Search Engine Optimization – Do It Yourself!" ser[...]
jQuery Object Oriented Plugins
Many people have asked me, if jQuery is object oriented and how they c[...]
Spring-MVC Tutorial (Part 1)
Overview This document is a step-by-step guide on how to de[...]
Animated scroll to anchor method with jQuery
It's a one line but can add a really nice effect to your website. f[...]
RECENT POSTS
How to calibrate Samsung Galaxy battery
There is no guarantee that this method will work for you. However it d[...]
Real Estate Social Network new Toronto Startup
Wanted to write for a long time about a new startup for Real Estate ag[...]
Eclipse Keyboard Shortcuts for Developers
Eclipse Navigation Shortcuts Every Java Programmer Should Know Ctrl [...]
Duplicated Content
This is Part 4 of "Search Engine Optimization – Do It Yourself!" ser[...]
301 Redirect
There are many ways how you can do 301 redirect, I will mention just t[...]





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,
useful info, this link also would be useful: http://www.javabeat.net/2012/04/parsing-json-using-java-and-gson-library/.
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);.