Wednesday, December 3, 2014

Playing with JSON in Java.

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. It is based on a subset of the JavaScript Programming LanguageStandard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

In  this tutorial we will learn how to parse JSON or how to convert a JSON String into java collection to extract the information we want.
Suppose I have one  JSON String, without parsing, It's just like string, all you can do is just call  the methods of string class on it.
To convert it into meaningful data structure you have to parse it.  plenty of jars are  available out there to parse. Internal working is same.

Here are we are using following jars. if you have other jars, working will be same

jackson-annotations-2.4.0.jar
jackson-core-2.4.2.jar
jackson-databind-2.4.2.jar


JSON to Collection

Sample JSON String

{
  "name": "satya",
  "designation": "abc",
  "hobbies": [
    "cricket",
    "running"
  ]
}


Save it into a variable, say simpleJson.

ObjectMapper mapper = new ObjectMapper();
Map<String ,Object> person =mapper.readValue(simpleJson ,new TypeReference<Map<String,Object>>() {
} );

System.out.println(person);

Here we are printing the map we are getting.
output will be {name=satya, designation=abc, hobbies=[cricket, running]}

Typereference is the format in which we want the output, It totally depends on the json input.
we can see by json that some keys have value as string and some have as lists, So we took a map where key are strings and values are objects(so it can contain anything.)


Collection to JSON

Further if you want to convert a collection into JSON. There is one more step and you are good to go.

Map<String,Object> person= new HashMap<String,Object>();
person.put("name", "satya");
person.put("designation", "abc");
List<String> list = new ArrayList<String>();
list.add("cricket");
list.add("running");
person.put("hobbies", list);

ObjectMapper mapper = new ObjectMapper();
String simpleJson= mapper.writeValueAsString(person);

System.out.println(simpleJson);

Output: 

{
  "name": "satya",
  "designation": "abc",
  "hobbies": [
    "cricket",
    "running"
  ]
}
This is the same JSON for which we got a map in previous example.

After these two examples you know how to convert a JSON into Collection and Collection to JSON.

Happy Coding!






This can be also used to transfer huge amount of data from server to client, So also useful in RPC

1 comment:

  1. this seems to be best way to parse and operate upon JSON with ease. Kudos Satya \0/

    ReplyDelete