Java – Read JSON Data Simple Example

In below example, it uses JSONParser to read and display JSON data from a file named “test.json“ using JSON.simple, a simple Java library for JSON processing.

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonSimpleExample {
     public static void main(String[] args) {

	JSONParser parser = new JSONParser();

	try {

		Object obj = parser.parse(new FileReader("c:\\test.json"));

		JSONObject jsonObject = (JSONObject) obj;

		String name = (String) jsonObject.get("name");
		System.out.println(name);

		long age = (Long) jsonObject.get("age");
		System.out.println(age);

		// loop array
		JSONArray msg = (JSONArray) jsonObject.get("messages");
		Iterator<String> iterator = msg.iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}

	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} catch (ParseException e) {
		e.printStackTrace();
	}

     }

}

Output:

prasanna
25
msg 1
msg 2
msg 3

Java – Write JSON Data Simple Example

In below example, it writes JSON data via JSONObject and JSONArray, and save it into a file named “test.json“ using JSON.simple, a simple Java library for JSON processing.

import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class JsonSimpleExample {
public static void main(String[] args) {

JSONObject obj = new JSONObject();
obj.put("name", "prasanna");
obj.put("age", new Integer(25));

JSONArray list = new JSONArray();
list.add("msg 1");
list.add("msg 2");
list.add("msg 3");

obj.put("messages", list);

try {

FileWriter file = new FileWriter("c:\\test.json");
file.write(obj.toJSONString());
file.flush();
file.close();

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

System.out.print(obj);

}

}

Output: (see content of file “test.json”)

{
“age”:25,
“name”:”prasanna”,
“messages”:["msg 1","msg 2","msg 3"]
}

Java – Read XML File – SAX Parser

SAX Parser is faster and uses less memory than DOM parser.

file.xml

<?xml version="1.0"?>
<company>
    <staff>
        <firstname>prasanna</firstname>
        <lastname>sherekar</lastname>
        <nickname>pashyaa</nickname>
        <salary>100000</salary>
    </staff>
    <staff>
        <firstname>james</firstname>
        <lastname>anderson</lastname>
        <nickname>lolo</nickname>
        <salary>200000</salary>
    </staff>
</company>

ReadXMLFile.java

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ReadXMLFile {

   public static void main(String argv[]) {

    try {

	SAXParserFactory factory = SAXParserFactory.newInstance();
	SAXParser saxParser = factory.newSAXParser();

	DefaultHandler handler = new DefaultHandler() {

	boolean bfname = false;
	boolean blname = false;
	boolean bnname = false;
	boolean bsalary = false;

	public void startElement(String uri, String localName,String qName,
                Attributes attributes) throws SAXException {

		System.out.println("Start Element :" + qName);

		if (qName.equalsIgnoreCase("FIRSTNAME")) {
			bfname = true;
		}

		if (qName.equalsIgnoreCase("LASTNAME")) {
			blname = true;
		}

		if (qName.equalsIgnoreCase("NICKNAME")) {
			bnname = true;
		}

		if (qName.equalsIgnoreCase("SALARY")) {
			bsalary = true;
		}

	}

	public void endElement(String uri, String localName,
		String qName) throws SAXException {

		System.out.println("End Element :" + qName);

	}

	public void characters(char ch[], int start, int length) throws SAXException {

		if (bfname) {
			System.out.println("First Name : " + new String(ch, start, length));
			bfname = false;
		}

		if (blname) {
			System.out.println("Last Name : " + new String(ch, start, length));
			blname = false;
		}

		if (bnname) {
			System.out.println("Nick Name : " + new String(ch, start, length));
			bnname = false;
		}

		if (bsalary) {
			System.out.println("Salary : " + new String(ch, start, length));
			bsalary = false;
		}

	}

     };

       saxParser.parse("c:\\file.xml", handler);

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

   }

}

Page 1 of 3123