Creating & Parsing JSON data with Java Servlet/Struts/JSP

[ad name=”AD_INBETWEEN_POST”] JSON (JavaScript Object Notation) is a lightweight computer data interchange format. It is a text-based, human-readable format for representing simple data structures and associative arrays (called objects). The JSON format is specified in RFC 4627 by Douglas Crockford. The official Internet media type for JSON is application/json. The JSON format is often used for transmitting structured data over a network connection in a process called serialization. Its main application is in AJAX web application programming, where it serves as an alternative to the traditional use of the XML format.

Supported data types

java logo
  1. Number (integer, real, or floating point)
  2. String (double-quoted Unicode with backslash escapement)
  3. Boolean (true and false)
  4. Array (an ordered sequence of values, comma-separated and enclosed in square brackets)
  5. Object (collection of key/value pairs, comma-separated and enclosed in curly brackets)
  6. null

Syntax

The following example shows the JSON representation of an object that describes a person. The object has string fields for first name and last name, contains an object representing the person’s address, and contains a list of phone numbers (an array).
{ "firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 }, "phoneNumbers": [ "212 732-1234", "646 123-4567" ] }
Code language: JavaScript (javascript)

Creating JSON data in Java

JSON.org has provided libraries to create/parse JSON data through Java code. These libraries can be used in any Java/J2EE project including Servlet, Struts, JSF, JSP etc and JSON data can be created. Download JAR file json-rpc-1.0.jar (75 kb) Use JSONObject class to create JSON data in Java. A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
import org.json.JSONObject; ... ... JSONObject json = new JSONObject(); json.put("city", "Mumbai"); json.put("country", "India"); ... String output = json.toString(); ...
Code language: Java (java)
Thus by using toString() method you can get the output in JSON format.

JSON Array in Java

A JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas separating the values. The internal form is an object having get and opt methods for accessing the values by index, and put methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object. The constructor can convert a JSON text into a Java object. The toString method converts to JSON text. JSONArray class can also be used to convert a collection of Java beans into JSON data. Similar to JSONObject, JSONArray has a put() method that can be used to put a collection into JSON object. Thus by using JSONArray you can handle any type of data and convert corresponding JSON output.

Using json-lib library

JSON-lib is a java library for transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans. Json-lib comes in two flavors, depending on the jdk compatibility. json-lib-x.x-jdk13 is compatible with JDK 1.3.1 and upwards. json-lib-x.x-jdk15 is compatible with JDK 1.5, includes support for Enums in JSONArray and JSONObject. Download: json-lib.jar Json-lib requires (at least) the following dependencies in your classpath:
  1. jakarta commons-lang 2.5
  2. jakarta commons-beanutils 1.8.0
  3. jakarta commons-collections 3.2.1
  4. jakarta commons-logging 1.1.1
  5. ezmorph 1.0.6

Example

package net.viralpatel.java; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONObject; public class JsonMain { public static void main(String[] args) { Map<String, Long> map = new HashMap<String, Long>(); map.put("A", 10L); map.put("B", 20L); map.put("C", 30L); JSONObject json = new JSONObject(); json.accumulateAll(map); System.out.println(json.toString()); List<String> list = new ArrayList<String>(); list.add("Sunday"); list.add("Monday"); list.add("Tuesday"); json.accumulate("weekdays", list); System.out.println(json.toString()); } }
Code language: Java (java)
Output:
{"A":10,"B":20,"C":30} {"A":10,"B":20,"C":30,"weekdays":["Sunday","Monday","Tuesday"]}
Code language: Java (java)

Using Google Gson library

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes; something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.

Gson Goals

  • Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
  • Allow pre-existing unmodifiable objects to be converted to and from JSON
  • Extensive support of Java Generics
  • Allow custom representations for objects
  • Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)

Google Gson Example

import java.util.List; import com.google.gson.Gson; public class Test { public static void main(String... args) throws Exception { String json = "{" + "'title': 'Computing and Information systems'," + "'id' : 1," + "'children' : 'true'," + "'groups' : [{" + "'title' : 'Level one CIS'," + "'id' : 2," + "'children' : 'true'," + "'groups' : [{" + "'title' : 'Intro To Computing and Internet'," + "'id' : 3," + "'children': 'false'," + "'groups':[]" + "}]" + "}]" + "}"; // Now do the magic. Data data = new Gson().fromJson(json, Data.class); // Show it. System.out.println(data); } } class Data { private String title; private Long id; private Boolean children; private List<Data> groups; public String getTitle() { return title; } public Long getId() { return id; } public Boolean getChildren() { return children; } public List<Data> getGroups() { return groups; } public void setTitle(String title) { this.title = title; } public void setId(Long id) { this.id = id; } public void setChildren(Boolean children) { this.children = children; } public void setGroups(List<Data> groups) { this.groups = groups; } public String toString() { return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups); }
Code language: Java (java)

Get our Articles via Email. Enter your email address.

You may also like...

37 Comments

  1. Navin says:

    Hi Team,
    I want to know how JSON helps in file upload in Java/Servlet/JSP.
    Sample code will be appriciated.

    regards,
    K. Navin.

  2. npk says:

    Hi Team,

    I need to have a simple example of the below
    1) Simple JSON example with Servlet
    2) Fileupload using JSON & Servlet

    Thanks for your help.

  3. Dharmesh says:

    Lot of questions left unanswered in this post.. was looking for something more elaborate .. but its ok .. will google it elsewhere

  4. Ratna Dinakar says:

    Instead of JSON RPC Jar.. try using this JSON-Lib. It has many advance features compared to library of json.org.

  5. Imran says:

    Hi ,

    Im trying to write a servlet that returns geoJSON, do I need to use the same library or does anybody have an idea how to convert JTS Geometry directly into JSON?

    thanks
    Imran
    Lahore, Pakistan

  6. chirag Patil says:

    can anyone have JSON java tutorial with output?
    If anyone has then plz contact me on [email protected]

  7. Hitesh jain says:

    Hi,
    I need to use json object in java and in javascript and in jsp….can any one help me how to populate it on the jsp. ASAP

    • durgesh says:

      Hi ,
      Hitesh
      if you gwill get your answer then please give me too.

  8. Vinod Halde says:

    Hi,
    I need to use json object in java and in javascript and in jsp….can any one help me how to populate it on the jsp. and also I need to have a simple example of the below
    1) Simple JSON example with Servlet

  9. Kamal says:

    Hi,

    Please I am interested to get the source code for the example.
    Thanks

  10. Subramani says:

    HI,
    i need to work with servlet and json using dropdownlist in html page to retrive the values from database selecting dropdownlist in html page…can u tell me how to do this

    Tanks..

  11. kris says:

    Good one…Thanks!

  12. manan shah says:

    Thnaks Viral….

    I like your freemarker’s articlea as well as this one…..

    thanks buddy.

    • manan shah says:

      Thnaks Viral….

      I like your freemarker’s article as well as this one…..

      thanks buddy.

  13. Parthiban says:

    Hi,
    I have the following json string

    {"records":
    	{"data":
    		{"featureName":" ","fields":"{@pref_lang= eng}","ruleName":"RULE_HSIA_2","weightage":"93","indexNo":"1"}}}
    


    By using Google gson, can u tell me how can i create pojo class for the above nested json string ?

  14. Siva says:

    Thanks Viral….

    This article is looking good.

  15. mike says:

    I want to use geojson but don’t know how to install it.
    Is it a jar file or a javascript file you need to have in the classpath.

  16. Vaibhav says:

    well i followed this and generated the JSONObject and returned it.
    How to parse this using Jquery ?

    I Populated the list of String with Student Names say, and then accumulated the List to JsonObject and returned this object. How to parse this JSON object such that i could display the Names line by Line inside a . Please Help

  17. Sarma says:

    Hi..I need to take the values from database and need to save in json file for plotting bar graphs using D3 charts..pls help

  18. kiran says:

    how to retrive the data from multiple files in to html using jsplumb
    can post me an example in which i need to construct Network graph in my application

  19. Jaydeep says:

    Thanks viral…
    This was helpful example…

  20. sheela says:

    Nice Site..Keep UP.. :)

  21. Shirish says:

    I got the below Error when I used the above code

    Mar 13, 2013 6:30:55 PM org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet [appServlet] in context with path [/csus] threw exception [Handler processing failed; nested exception is java.lang.NoClassDefFoundError: org/json/JSONObject] with root cause
    java.lang.ClassNotFoundException: org.json.JSONObject

  22. dinesh says:

    i have the douts how i can send the above map to the java script

  23. joshua says:

    How can use json with Jquery easyui,because i m not able to get the data on the grid.

  24. prashansa says:

    hello
    I have String in this formate [{“id”:6,”children”:[{“id”:8,”children”:[{“id”:7,”children”:[{“id”:5}]}]}]},{“children”:[{“children”:[{}]}]},{}]
    How can I get key and value.Please Rply.

    import java.util.List;
    class Data {
        private String title;
        private Long id;
        private Boolean children;
        private List<Data> groups;
     
        public String getTitle() { return title; }
        public Long getId() { return id; }
        public Boolean getChildren() { return children; }
        public List<Data> getGroups() { return groups; }
     
        public void setTitle(String title) { this.title = title; }
        public void setId(Long id) { this.id = id; }
        public void setChildren(Boolean children) { this.children = children; }
        public void setGroups(List<Data> groups) { this.groups = groups; }
     
        public String toString() {
            return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
        }
    }
    

    import java.util.List;
    import com.google.gson.Gson;
     
    public class Test {
     
        public static void main(String... args) throws Exception {
        String jj=	"{'id':5},{'children':[{'id':6},{'children':[{'id':7},{}]}]},{'id':8},{}";
            
            // Now do the magic.
            Data data = new Gson().fromJson(jj, Data.class);
            System.out.println(data);
        }
     
    }
    
     

    Thanks
    prashansa

    • Abakasha says:

      hello prashansa can u tell me why this toString() is there inside Data class …what is its need

  25. prashansa says:

    hello,

    When I am Using your code it’s giving an error

    Exception in thread "main" com.google.gson.JsonParseException: Failed parsing JSON source: {'title': 'Computing and Information systems','id' : 1,'children' : 'true','groups' : [{'title' : 'Level one CIS','id' : 2,'children' : 'true','groups' : [{'title' : 'Intro To Computing and Internet','id' : 3,'children': 'false','groups':[]}]}]} to Json
    	at com.google.gson.Gson.fromJson(Gson.java:328)
    	at com.google.gson.Gson.fromJson(Gson.java:299)
    	at Test.main(Test.java:27)
    Caused by: com.google.gson.TokenMgrError: Lexical error at line 1, column 2.  Encountered: "\'" (39), after : ""
    	at com.google.gson.JsonParserTokenManager.getNextToken(JsonParserTokenManager.java:762)
    	at com.google.gson.JsonParser.jj_ntk(JsonParser.java:439)
    	at com.google.gson.JsonParser.JsonObject(JsonParser.java:45)
    	at com.google.gson.JsonParser.parse(JsonParser.java:21)
    	at com.google.gson.Gson.fromJson(Gson.java:323)
    	... 2 more
    

  26. Bittu says:

    Please help me to implement datatable with play and scala…..
    I am very thankful if anyone help me….

  27. This tool will help to debug and analyse JSON data http://codebeautify.org/jsonviewer

  28. bhargav says:

    I want to get json in jsp from my android application registration form.
    Is it possible ?

  29. pruthvi says:

    i m in need of code for json with servlet using search.pls help me

  30. amit singh says:

    i need a example
    i want to fetch data from database and send to jsp page with json array format . because i want to create dynamic table and that data using in google chart please send me a rxample

  31. prakyath says:

    could you please help me to create external json file..

  32. nicu says:

    hello , i have a question, i can parse this json :

    private String strJSONValue = “{ \”Android\” :[{\”song_name\”:\”Gimme Dat\”,\”song_id\”:\”1932\”,\”artist_name\”:\”Sidney Samson (Feat. Pitbull & Akon)\”},{ \”song_name\”:\”F-k The Money (Remix)\”,\”song_id\”:\”73\”,\”artist_name\”:\”B.o.B. (Feat. Wiz Khalifa)\”}] }”;

    like this :

    String OutputData = “”;
    JSONObject jsonResponse;

    try {

    /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
    jsonResponse = new JSONObject(strJSONValue);

    /***** Returns the value mapped by name if it exists and is a JSONArray. ***/
    /******* Returns null otherwise. *******/
    JSONArray jsonMainNode = jsonResponse.optJSONArray(“Android”);

    /*********** Process each JSON Node ************/

    int lengthJsonArr = jsonMainNode.length();

    for(int i=0; i < lengthJsonArr; i++)
    {
    /****** Get Object for each JSON node.***********/
    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

    /******* Fetch node values **********/
    int song_id = Integer.parseInt(jsonChildNode.optString("song_id").toString());
    String song_name = jsonChildNode.optString("song_name").toString();
    String artist_name = jsonChildNode.optString("artist_name").toString();

    OutputData += "Node : \n\n "+ song_id +" | "
    + song_name +" | "
    + artist_name +" \n\n ";
    //Log.i("JSON parse", song_name);
    }

    /************ Show Output on screen/activity **********/
    showMessage(OutputData, "STunes") ;

    } catch (JSONException e) {

    showMessage("STunes", "Error");}

    }

    My question is how i cand parse this json :

    {"music":[{"external_ids":{"isrc":"GBAMC9800041","upc":"731453835122"},"play_offset_ms":117680,"external_metadata":{"deezer":{"album":{"id":1939301},"artists":[{"id":119}],"genres":[{"id":132}],"track":{"id":20309341}}},"title":"Whiskey In The Jar","duration_ms":"0","album":{"name":"Garage Inc."},"acrid":"01272c3cd88a9b38e268ed038989b885","genres":[{"name":"Pop"}],"artists":[{"name":"Metallica"}]}],"timestamp_utc":"2015-08-13 05:43:55"}

    I can't find an answer

  33. Biosync says:

    Very helpful…

    Thanks.

  34. Nilesh it says:

    please send simple exmple of json convert the html form field values in json object and set it to the server means jsp page then jsp page display that values which are user entered

Leave a Reply

Your email address will not be published. Required fields are marked *