在Java中解析JSON字符串时,为什么会说;“对……没有价值”;

在Java中解析JSON字符串时,为什么会说;“对……没有价值”;,java,android,json,parsing,Java,Android,Json,Parsing,所以我从一个传感器插座上读取数据 { "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,

所以我从一个传感器插座上读取数据

{
    "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"
    }
}
存储的是由
StringBuilder sb
生成的

我不太熟悉解析JSON字符串(以前从未做过),但我想获得
co_mV
no2_mV
数据。我想我不必使用
JSONArray
或其他什么东西。所以我试过这个

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

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

我做错了什么

您的JSON数据保存在另一个名为
d
的JSON对象中,因此您需要先访问
d
,然后才能访问其余数据

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"));
请尝试以下代码:

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

您正在尝试从父json参数访问子json参数。尝试:

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

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

显然,在json
{“d”:{…}
中没有
co_mV
的值,只有
d
。。。是时候学习一些json基础了是的,你是对的,对不起。谢谢你的回答@Selvin
            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"));