簡體   English   中英

如何打印json對象和數組值?

[英]How can i print json objects and array values?

在結果字符串中,我具有要解析的全部數據,我需要在值中打印當前條件。

current_condition": [ {"cloudcover": "75", "humidity": "71", "observation_time": "06:55 AM", "precipMM": "0.6", "pressure": "1009", "temp_C": "32", "temp_F": "90", "visibility": "10", "weatherCode": "116", "weatherDesc": [ {"value": "Partly Cloudy" } ], "weatherIconUrl": [ {"value": "http:\/\/cdn.worldweatheronline.net\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png" } ], "winddir16Point": "S", "winddirDegree": "170", "windspeedKmph": "9", "windspeedMiles": "6" } ]

這是我的json數組,在這里我需要在值中包含cloudcover, weatherDesc數組,如何打印這些值。 這是我做的

JSONParser parser = new JSONParser();
        Object obj1 = parser.parse(Result);
        JSONObject jobj = (JSONObject) obj1;
        JSONObject dataResult = (JSONObject) jobj.get("data");
        JSONArray current_condition = (JSONArray) dataResult.get("current_condition");
        //out.println(current_condition);
        for (int i = 0; i < current_condition.size(); i++) {

        }

在for循環內如何重復和打印值,有人可以幫助我嗎,謝謝。

假設您使用的是org.json,我將對數組進行如下迭代:

public static void main(String[] args) {
    String json = "{ \"data\": { \"current_condition\": [ {\"cloudcover\": \"75\", \"humidity\": \"71\", \"observation_time\": \"06:55 AM\", \"precipMM\": \"0.6\", \"pressure\": \"1009\", \"temp_C\": \"32\", \"temp_F\": \"90\", \"visibility\": \"10\", \"weatherCode\": \"116\", \"weatherDesc\": [ {\"value\": \"Partly Cloudy\" } ], \"weatherIconUrl\": [ {\"value\": \"http:\\/\\/cdn.worldweatheronline.net\\/images\\/wsymbols01_png_64\\/wsymbol_0002_su‌​nny_intervals.png\" } ], \"winddir16Point\": \"S\", \"winddirDegree\": \"170\", \"windspeedKmph\": \"9\", \"windspeedMiles\": \"6\" } ]}}";
    try {
        JSONObject jObj = new JSONObject(json);
        JSONObject dataResult = jObj.getJSONObject("data");
        JSONArray jArr = (JSONArray) dataResult.getJSONArray("current_condition");
        for(int i = 0; i < jArr.length();i++) {
            JSONObject innerObj = jArr.getJSONObject(i);
            for(Iterator it = innerObj.keys(); it.hasNext(); ) {
                String key = (String)it.next();
                System.out.println(key + ":" + innerObj.get(key));
            }
        }
    }
    catch (JSONException e) {
        e.printStackTrace();
    }

}

您是否使用json簡單?,如果是,請嘗試:

for (JSONObject object : current_condition) {
    System.out.println("cloudcover : " + object.get("cloudcover"));
    System.out.println("humidity : " + object.get("humidity"));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM