Java – The easiest way to parse JSON strings

The easiest way to parse JSON strings… here is a solution to the problem.

The easiest way to parse JSON strings

How do I navigate a JSON string from one key to another nested key and get the value? I have the following string

{ "data" : { "current_condition" : [ { "cloudcover" : "75",
            "humidity" : "29",
            "observation_time" : "07:59 PM",
            "precipMM" : "0.0",
            "pressure" : "1011",
            "temp_C" : "19",
            "temp_F" : "67",
            "visibility" : "16",
            "weatherCode" : "116",
            "weatherDesc" : [ { "value" : "Partly Cloudy" } ],
            "weatherIconUrl" : [ { "value" : "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png" } ],
            "winddir16Point" : "N",
            "winddirDegree" : "350",
            "windspeedKmph" : "26",
            "windspeedMiles" : "16"
          } ],
      "request" : [ { "query" : "01801",
            "type" : "Zipcode"
          } ],
      "weather" : [ { "date" : "2011-05-09",
            "precipMM" : "0.0",
            "tempMaxC" : "19",
            "tempMaxF" : "65",
            "tempMinC" : "10",
            "tempMinF" : "50",
            "weatherCode" : "113",
            "weatherDesc" : [ { "value" : "Sunny" } ],
            "weatherIconUrl" : [ { "value" : "http://www/images/wsymbols01_png_64/wsymbol_0001_sunny.png" } ],
            "winddir16Point" : "NNW",
            "winddirDegree" : "348",
            "winddirection" : "NNW",
            "windspeedKmph" : "24",
            "windspeedMiles" : "15"
          },
          { "date" : "2011-05-10",
            "precipMM" : "0.1",
            "tempMaxC" : "13",
            "tempMaxF" : "56",
            "tempMinC" : "12",
            "tempMinF" : "53",
            "weatherCode" : "122",
            "weatherDesc" : [ { "value" : "Overcast" } ],
            "weatherIconUrl" : [ { "value" : "http://www/images/wsymbols01_png_64/wsymbol_0004_black_low_cloud.png" } ],
            "winddir16Point" : "NNE",
            "winddirDegree" : "12",
            "winddirection" : "NNE",
            "windspeedKmph" : "31",
            "windspeedMiles" : "19"
          }
        ]
    } }

So I answer my own question:
If someone else wants to get value quickly: this is what I’m looking for.

JSONObject j = new JSONObject(strResponse);

String weatherDesc = jObject.getJSONObject("data").getJSONArray("weather").getJSONObject(0).getJSONArray("weatherDesc").getJSONObject(0).getString("value");

Solution

Almost all languages have JSON libraries. If you make a suggestion, I might be able to point something out for you.

In the meantime, here are some:

Wait a minute. I recommend a quick Google search for the language of your choice.

Related Problems and Solutions