JSONExeption没有价值

Max*_*Max 0 android json jsonobject

我有字符串对象:

String qwe = "{\"myObj\":" + "{" + "\"first\":123," + "\"second\":111.0}" +"}";

我的代码

private static final String TAG_FIRST = "first";
res = new JSONObject(qwe);
Double q1 = res.getDouble(TAG_FIRST);
Run Code Online (Sandbox Code Playgroud)

我有"先没有价值"的例外.

我做错了什么?

抱歉我的英语不好.最好的祝福

T.J*_*der 5

您的JSON使用该属性定义了一个对象myObj.值myObj是一个不同的对象.物体有一个first属性.如果我们只查看JSON并使用缩进,这可能会更清楚:

{
    "myObj": {
        "first": 123,
        "second": 111.0
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,首先你必须拿到myObj对象,然后得到first来自.

private static final String TAG_MYOBJ = "myObj";
private static final String TAG_FIRST = "first";
res = new JSONObject(qwe);
JSONObject myObj = res.getJSONObject(TAG_MYOBJ);
Double q1 = myObj.getDouble(TAG_FIRST);
Run Code Online (Sandbox Code Playgroud)

或者,如果您不打算拥有该外层,您可能希望您的JSON字符串如下所示:

String qwe =
+ "{"
+ "\"first\":123,"
+ "\"second\":111.0"
+"}";
Run Code Online (Sandbox Code Playgroud)

该字符串包含此JSON:

{
    "first": 123,
    "second": 111.0
}
Run Code Online (Sandbox Code Playgroud)

...它可以正常使用您的原始代码(此处重复):

private static final String TAG_FIRST = "first";
res = new JSONObject(qwe);
Double q1 = res.getDouble(TAG_FIRST);
Run Code Online (Sandbox Code Playgroud)