How to parse JSON with Java Java 05.12.2013

JSON stands for (Java Script Object Notation) and it's a simple and light-weight data interchange format. A JSON object is an unordered set of key/value pairs. A JSON array is an ordered collection of values.

I'm going to use org-json-java.

Simple example with json object creation

// import org.json.JSONException;
// import org.json.JSONObject;
try {
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("name", "John");
    jsonObj.put("age", "29");
    System.out.println(jsonObj.toString());
} catch(JSONException ex) {
    ex.printStackTrace();
}

You can compile example with following command

javac -cp org.json-20120521.jar J.java && java -cp .:org.json-20120521.jar J

For extractng JSON from string use next statements

JSONObject json = new JSONObject(jsonString);
String name = json.getString("name");
int age = json.getString("age");

The org.json.JSONArray class represents an array. Each element in the array can be accessed using index.

String jsonString = "{ \"number\": [1, 2, 3, 4] }";
JSONObject obj = new JSONObject(jsonString);
JSONArray arr = obj.getJSONArray("number");
for (int i = 0; i < arr.length(); i++)
    System.out.println(arr.getInt(i));

Write JSON object to file

// import java.io.FileWriter;
// import java.io.IOException;

try {
    FileWriter file = new FileWriter("/home/proft/temp/tmp.json");
    file.write(jsonObj.toJSONString());
    file.flush();
    file.close();
} catch (IOException e) {
    e.printStackTrace();
}

Read JSON object from file

// import org.json.JSONObject;
// import org.json.JSONTokener;
// import java.io.FileNotFoundException;
// import java.io.FileReader;
// import java.io.IOException;

try {
    FileReader reader = new FileReader("/home/proft/temp/tmp.json");
    JSONTokener tokener = new JSONTokener(reader);
    JSONObject obj = new JSONObject(tokener);
    System.out.println(obj.getString("name"));
} catch (IOException e) {
    e.printStackTrace();
}

Read JSON object from URL

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

import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class J {
    public static void main(String args[]) {
        try {
            JSONArray json = readJsonFromUrl("http://url.com/api/objects/?format=json");
            JSONObject obj = (JSONObject)json.get(5);
            System.out.println(obj.get("title"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    public static JSONArray readJsonFromUrl(String url) throws IOException {
        // String s = URLEncoder.encode(url, "UTF-8");
        // URL url = new URL(s);
        InputStream is = new URL(url).openStream();
        JSONArray json = null;
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            json = new JSONArray(jsonText);
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            is.close();
        }
        return json;
    }
}

With Python 2.6+ we can prettify our JSON in terminal

echo '{"name":"John","age":"29"}' | python -mjson.tool

Also we can use jshon or jq.