Thursday, December 22, 2016

Parsing JSON using Jackson Library

Apart from being able to parse a json using the json libraries as shown here, another interesting way to parse a json is using the jackson library. To begin using this method, we add the following entry to our pom -

pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.3</version>
</dependency>

And we use the following json file that we read from our resource folder -

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 Jackson library essentially maps json elements to class variables. So, to map the values, a model consisting of one or more classes, having the same structure as the json is needed. For our current json, we need two classes - one for the original json and one for the address.

The two models are as follows -

Address.java


public class Address {
        String street;
        String city;

        //Getters and Setters
}

JsonEntry.java

import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;

public class JsonEntry {
        @JsonProperty("firstname")
        String firstName;

        @JsonProperty("lastname")
        String lastName;

        Address address;
        List<String> books;

        //Getters and Setters
}

The JsonProperty annotation is used when the name of the json field varies from the variable name. It is not needed in the case when the name of the field is the same as the name of the variable.

The complete java file which parses and prints the json is given below -

JsonParser.java

package json.parser;

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

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

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

   JsonEntry jsonParsed = parseJson(json, mapper);

   System.out.println("-----Printing Json--------------");
   printJson(jsonParsed);

   System.out.println("\n-----Pretty Printing Json--------------");
   prettyPrintJson(jsonParsed, mapper);
  } 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 JsonEntry parseJson(String jsonString, ObjectMapper mapper) {
  JsonEntry jsonEntry = null;

  try {
   // Convert JSON string to Object
   jsonEntry = mapper.readValue(jsonString, JsonEntry.class);
  } catch (JsonGenerationException e) {
   e.printStackTrace();
  } catch (JsonMappingException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

  return jsonEntry;

 }

 private static void printJson(JsonEntry json) {
  System.out.println("First Name: " + json.getFirstName());
  System.out.println("Last Name: " + json.getLastName());

  System.out.println("Street: " + json.getAddress().getStreet());
  System.out.println("City: " + json.getAddress().getCity());

  for (int i = 0; i < json.getBooks().size(); i++) {
   System.out.println("Book " + (i + 1) + ": " + json.getBooks().get(i));
  }
 }

 private static void prettyPrintJson(JsonEntry json, ObjectMapper mapper) throws JsonProcessingException {
  String prettyPrint = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
  System.out.println(prettyPrint);
 }
}

The method parseJson() maps the json string to the object model definition. printJson() and prettyPrintJson()are simply outputting the values of the mapped json.


See also -
Parsing Json using Json Libraries

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

Friday, August 26, 2016

Converter - Weight


A small javascript application to convert values between the different units of weight.




Value Unit
0
Milligram (mg)
0
Gram (g)
0
Kilogram (Kg)
0
Metric Ton (t)
0
Grain
0
Ounce (oz.)
0
Pound (lb.)


Other converters -

Length Converter

Saturday, August 13, 2016

Converter - Length


This is a small application, made with a little help from a friend called Anjuma, out of Javascript, to convert the length from different units to different units. Type in the value to start converting -



Value Unit
0
Millimeter (mm)
0
Centimeter (cm)
0
Meter (mt)
0
Kilometer (km)
0
Inch (in)
0
Foot (ft)
0
Yard (yd)
0
Mile (mi)
0
Nautical Mile (nm)
0
League


Other converters -

Weight converter

Saturday, July 30, 2016

Aspect Ratio Calculator

Enter the values for a and b to get the ratio first. And then give the desired values for either x or y.

a =

x =

0
----
0

b =

y =



Wednesday, July 27, 2016

View CSV text online

This small application uses javascript to parse csv text and display the contents in a table. It provides easy readability for the clustered text in a CSV file.

To begin simply copy the csv text and paste it in the text box below. You can optionally choose a delimiter. The default is ofcourse a ','. The delimiter can hold more than one charecter.




Delimiter: Seperate header

Monday, June 27, 2016

Parsing XMLs with DOM Parser

DOM parsers are the simpler of the two parsers, the other being SAX parser. Its is programmetically less complicated but is also less efficient compared to sax. The DOM parser loads the whole document into the main memory and then parses the whole document all at once as opposed to parsing on encountering in SAX parser. The obvious drawback to loading the full file in memoory is that the efficiency of parsing reduces with the increase in size of the document. Not to mention, documents that don't fit in the memory cannot be parsed.

To understand DOM parser, we take an example xml file and parse it using DOM. Lets consider the following xml -

testXML.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<first>
    <second atName="one">
        <number id="one">1</number>
        <number id="two">2</number>
    </second>
    
    <second atName="two"> 
        <number id="one">1</number>
        <number id="two">2</number>
    </second>
</first>

Our goal is to parse this whole document and output the same using DOM parser. Before beginning with the example lets look into some helper classes and basic methods -

DocumentBuilder - It defines the API to generate the DOM document tree from an XML. Its usually created by using the DocumentBuilderFactory.newInstance().

Node - It is an interface which represents a node in the DOM tree.

Attr - This is the interface which represents the attributes of a node.

NamedNodeMap - This represents the list of attributes that a node holds.

In our example, the main() method first generates the DOM tree and the processNode() method traverses this tree printing the nodes as it encounters them.

DomParser.java


public class DomParser {

    public static void main(String[] args) {
        try {
            File file = new File("src/testXML.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(file);
            doc.getDocumentElement().normalize();

            String tab = "";

            System.out.println("Staring Parsing...");

            //Process root Node
            Node root = doc.getDocumentElement();
            System.out.println(root.getNodeName());
            processNode(root, "\t" + tab);

            System.out.println("Parsing Complete...");

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

    public static void processNode(Node node, String tab) {
        try {
            NodeList children = node.getChildNodes();

            for (int i = 0; i < children.getLength(); i++) {
                Node ele = children.item(i);

                //Printing the node name or the text value in case of a Text node
                if (ele.getNodeName().equals("#text")) {
                    System.out.print(" " + ele.getNodeValue());
                } else {
                    System.out.print(tab + ele.getNodeName());
                }

                //Printing attributes of the current node.
                if (ele.hasAttributes()) {
                    NamedNodeMap attrs = ele.getAttributes();
                    for (int j = 0; j < attrs.getLength(); j++) {
                        Attr attribute = (Attr) attrs.item(j);
                        System.out.print(" " + attribute.getName() + "=" + attribute.getValue());
                    }
                }

                //Process children 
                processNode(ele, "\t" + tab);
            }

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

    }

}

The text nodes appear with a "#text" in them. This nodes accordingly dealt with. The method processNode()is recursively called as it traverses through the whole tree. The output for the above program is as follows -

Output


Staring Parsing...
first
 
     second atName=one 
          number id=one 1 
          number id=two 2 
     
    
     second atName=two  
          number id=one 1 
          number id=two 2 
     
Parsing Complete...


The DOM parser is not a very efficient parser, but for small documents, it can be very useful.