Thursday, December 22, 2016

Parsing Json using Json Libraries

In this example we try to parse a json file using the json libraries. I have used the json library found here. So, I added the following dependency to my POM.

pom.xml

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
</dependency>

In my workspace, the follwing json file is used and read from the resource directory. The json can also be provided directly as a string or simply read from a file.

sherlock.json

{
 "firstname": "Sherlock",
 "lastname": "Holmes",
 "address": {
  "street": "221B, Baker Street",
  "city": "London"
 },
 "books": ["A Study in Scarlet", "The Sign of the Four", "The Hound of the Baskervilles"]
}


The code uses the class JSONObject and JSONArray to parse through the json and print accordingly. The code for the parser is as follows -


package json.reader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonReader {
 public static void main(String[] args) {
  String json;
  try {
   ClassLoader classLoader = JsonReader.class.getClassLoader();
   InputStream in = classLoader.getResourceAsStream("json/sherlock.json");
   json = convertToString(in);

   parseJson(json);

  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 private static String convertToString(InputStream in) throws IOException {
  StringBuilder sb = new StringBuilder();
  BufferedReader br = new BufferedReader(new InputStreamReader(in));

  String line;

  while ((line = br.readLine()) != null) {
   sb.append(line).append("\n");
  }

  return sb.toString();

 }

 private static void parseJson(String jsonString) throws JSONException {
  JSONObject obj = new JSONObject(jsonString);

  System.out.println("First Name: " + obj.getString("firstname"));
  System.out.println("Last Name: " + obj.getString("lastname"));

  JSONObject address = obj.getJSONObject("address");
  System.out.println("Street: " + address.getString("street"));
  System.out.println("City: " + address.getString("city"));

  JSONArray books = obj.getJSONArray("books");
  for (int i = 0; i < books.length(); i++) {
   System.out.println("Book " + (i + 1) + ": " + books.get(i));
  }
 }
}

The responsibility of the method convertToString()is to take an InputStream as input and return the json as a string. The json string is then passed to the method parseJson() which reads throught the json one value at a time. The books is an array of string and hence is handled accordingly.

The output of the above program looks as below -

Output

First Name: Sherlock
Last Name: Holmes
Street: 221B, Baker Street
City: London
Book 1: A Study in Scarlet
Book 2: The Sign of the Four
Book 3: The Hound of the Baskervilles


See also -
Parsing JSON using Jackson Library

No comments:

Post a Comment