Kspr
Kspr

Reputation: 685

Parsing JSON string in Java, why does it say "No value for ..."

So I am reading data from a sensors socket which looks like

{
    "d": {
        "temp_mC":0,
        "humidity_ppm":28430,
        "pressure_Pa":101242,
        "temp2_mC":32937,
        "co_mV":238,
        "no2_mV":1812,
        "light_Lux":0,
        "noise_dB":79,
        "cputemp_C":34,
        "battery_mV":3155,
        "ts":"1970-01-01T00:01:08Z"
    }
}

Which is stored is built by a StringBuilder sb.

I am not very familiar with parsing JSON strings (never done it before), but I want to get the co_mV and no2_mV data. I figured I did not have to use JSONArray or something. So I tried this

 JSONObject parser = new JSONObject(sb.toString());
 System.out.println(parser.getInt("co_mV"));

This returns

 "org.json.JSONException: No value for co_mV"

What am I doing wrong?

Upvotes: 2

Views: 121

Answers (5)

Mukeshkumar S
Mukeshkumar S

Reputation: 795

            JSONObject jsonObject = new JSONObject(sb.toString());
            JSONObject jsonObject1 = jsonObject.getString("d");
            String co_mV = String.valueOf(jsonObject1.getString("co_mV"));
            String no2_mV = String.valueOf(jsonObject1.getString("no2_mV"));

Upvotes: 2

Bertram Gilfoyle
Bertram Gilfoyle

Reputation: 10235

Try this.

JSONObject parser = new JSONObject(sb.toString());
JSONObject parser_d = parser.getJSONObject("d");
System.out.println(parser_d.getInt("co_mV"));

Upvotes: 2

aloj
aloj

Reputation: 3240

You are trying to access to a child json param from parent one. Try:

JSONObject jsonObject = new JSONObject(sb.toString());
JSONObject dJsonObject = jsonObject.getJSONObject("d");
System.out.println(dJsonObject.getInt("co_mV"));

Upvotes: 2

Chetan Joshi
Chetan Joshi

Reputation: 5711

Try with below code:

JSONObject parser = new JSONObject(sb.toString());
JSONObject jsonObject = jsonObject.getJSONObject("d");
System.out.println(jsonObject .getInt("co_mV"));

Upvotes: 2

Michael Dodd
Michael Dodd

Reputation: 10280

Your JSON data is held within a second JSON object called d, so you need to access d first before you access the rest of your data.

JSONObject parser = new JSONObject(sb.toString());
JSONObject d = parser.getJSONObject("d");
System.out.println(d.getInt("co_mV"));
System.out.println(d.getInt("no2_mV"));

Upvotes: 2

Related Questions