Help get this topic noticed by sharing it on Twitter, Facebook, or email.
sarahkim (Official Rep) July 10, 2014 20:55

How to Parse JSON in Java

This is an excerpt from Java Web Services: Up and Running.

Use json-lib, a library which adds JSON support to any Java program. json-lib can take a String and turn it into a JSONObject which can then be used to retrieve specific attributes.

  1. Add this dependency to your project:

  2. Put the following JSON sample in your classpath:
    'mission':'apollo 11'}

  3. Load the resource from the classpath and parse this JSON as follows:
    package com.discursive.answers;


    import net.sf.json.JSONObject;
    import net.sf.json.JSONSerializer;


    public class JsonParsing {

    public static void main(String[] args) throws Exception {
    InputStream is =
    JsonParsing.class.getResourceAsStream( "sample-json.txt");
    String jsonTxt = IOUtils.toString( is );

    JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );
    double coolness = json.getDouble( "coolness" );
    int altitude = json.getInt( "altitude" );
    JSONObject pilot = json.getJSONObject("pilot");
    String firstName = pilot.getString("firstName");
    String lastName = pilot.getString("lastName");

    System.out.println( "Coolness: " + coolness );
    System.out.println( "Altitude: " + altitude );
    System.out.println( "Pilot: " + lastName );

Note that JSONSerializer returns a JSON object. This is a general object which could be a JSONObject or a JSONArray depending on the JSON you are trying to parse. In this example, since I know that the JSON is a JSONObject, I can cast the result directly to a JSONObject. If you are dealing with JSON that could return a JSONArray, you'll likely want to check the type of the object that is returned by toJSON.

This sample project is available on GitHub.

For more information about the json-lib project, see JSON-LIB project page.
2 people like
this idea
This topic is not open for comments or replies.