猿问

Java 获取嵌套的 JSON 对象/数组

使用的代码:


jObj = new JSONObject(json);

newJSONString = jObj.getString("payload");

JArray = new JSONArray(newJSONString);

这是 JArray 的样子:


[{"06:30:00":{"color":"grey","time_color":"black"},"06:45:00":{"color":"grey","time_color":"黑色的”}}]


现在我想遍历接收到的时间并打印它们的颜色,该怎么做?


我试过的:


for (int i = 0; i < JArray.length(); ++i) {

    JSONObject rec = null;

    try {

        rec = JArray.getJSONObject(i);

    } catch (JSONException e) {

        e.printStackTrace();

    }

    android.util.Log.e("print row:", String.valueOf(rec));

}

这只是给我这个输出:


{"06:30:00":{"color":"grey","time_color":"black"},"06:45:00":{"color":"grey","time_color":"black "}}


慕森王
浏览 152回答 2
2回答

九州编程

您得到此输出是因为您的 JSON 数组仅包含一个 JSON 对象,即 - {"06:30:00":{"color":"grey","time_color":"black"},"06:45:00 “:{“颜色”:“灰色”,“time_color”:“黑色”}}在回答您的问题之前,我建议您先了解一下 JSON 语法。它将帮助您有效地理解您的问题和答案。回到您的问题,为了从嵌套的 JSON 中获取“颜色”字段:遍历 JSON 对象中的键。在你的情况下,这些是 - “06:30:00”,“06:45:00”。您可以在 google 上搜索解决方案来遍历 java 中的 JSON 对象中的键。获取与给定键(时间)关联的嵌套对象 - 您可以为此使用 Json 库提供的 getJSONObject() 方法。从 json 对象获取“颜色”字段 - 您可以使用 Json 库为此提供的 optString() 或 getString() 方法 - 取决于您的字符串是强制性的还是可选的。这是针对您的问题的 Java 工作解决方案:public static void getColor(JSONObject payloadObject) {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; JSONArray keys = payloadObject.names();&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < keys.length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String key = keys.getString(i); // Here's your key&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JSONObject value = payloadObject.getJSONObject(key); // Here's your value - nested JSON object&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String color = value.getString("color");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(color);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } catch (JSONException e) {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; }}请注意,您收到的有效负载对象被视为 JSON 对象。希望这可以帮助。

慕哥9229398

使用Keys()返回的方法Iterator<String>,以便很容易迭代每个嵌套JSONfor (int i = 0; i < JArray.length(); ++i) {try {&nbsp; &nbsp;JSONObject rec = JArray.getJSONObject(i);&nbsp; &nbsp;Iterator<String> keys = rec.keys();&nbsp; &nbsp; while(keys.hasNext()) {&nbsp; &nbsp; &nbsp; String key1 = keys.next();&nbsp; &nbsp; &nbsp; JSONObject nested = rec.getJSONObject(key1);&nbsp; &nbsp;//{"color":"grey","time_color":"black"}&nbsp; &nbsp; &nbsp; //now again same procedure&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Iterator<String> nestedKeys = nested.keys();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;while(nestedKeys.hasNext())&nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;String key2 = nestedKeys.next();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("key"+"..."+key2+"..."+"value"+"..."+nested.getString(key2);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; }} catch (JSONException e) {&nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp;}android.util.Log.e("print row:", String.valueOf(rec));}
随时随地看视频慕课网APP

相关分类

Java
我要回答