Parse JSON in Java

JSON stands for JavaScript Object Notation, and it is based on a subset of JavaScript. As a data-exchange format, it is widely used in web programming. Here we show how to parse JSON data in Java using the org.json library.

A JSON object is an unordered set of key/value pairs. A JSON array is an ordered collection of values. The values themselves could be objects or arrays.

The following is an example JSON text. The value for the key "address" is an object, and the value for "phoneNumber" is an array.

{
    "name": "Alice",
    "age": 20,
    "address": {
        "streetAddress": "100 Wall Street",
        "city": "New York"
    },
    "phoneNumber": [
        {
            "type": "home",
            "number": "212-333-1111"
        },{
            "type": "fax",
            "number": "646-444-2222"
        }
    ]
}

The org.json.JSONObject class represents an object. The following code builds an object from a string, and then retrieves values by providing the keys.

String str = "{ \"name\": \"Alice\", \"age\": 20 }";
JSONObject obj = new JSONObject(str);
String n = obj.getString("name");
int a = obj.getInt("age");
System.out.println(n + " " + a);  // prints "Alice 20"

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

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

Example: Geocoding

Google Maps API provides geocoding services to find the latitude/longitude of an address. The service returns results in JSON. The following method geocoding() does the following:

  • Build a URL to access the geocoding service.
  • Read from the URL.
  • Build a JSON object for the content.
  • Retrieve the first result from an array of results.
  • Print out the information.
public static void geocoding(String addr) throws Exception
{
    // build a URL
    String s = "http://maps.google.com/maps/api/geocode/json?" +
                    "sensor=false&address=";
    s += URLEncoder.encode(addr, "UTF-8");
    URL url = new URL(s);

    // read from the URL
    Scanner scan = new Scanner(url.openStream());
    String str = new String();
    while (scan.hasNext())
        str += scan.nextLine();
    scan.close();

    // build a JSON object
    JSONObject obj = new JSONObject(str);
    if (! obj.getString("status").equals("OK"))
        return;

    // get the first result
    JSONObject res = obj.getJSONArray("results").getJSONObject(0);
    System.out.println(res.getString("formatted_address"));
    JSONObject loc =
        res.getJSONObject("geometry").getJSONObject("location");
    System.out.println("lat: " + loc.getDouble("lat") +
                        ", lng: " + loc.getDouble("lng"));
}

Related Posts

Comments

comments