如何打印json对象和数组值?

时间:2014-05-19 08:26:45

标签: java json

在结果字符串中,我有完整的数据用于解析,我需要在值内打印当前条件。

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循环中如何重复和打印值,任何人都可以帮助我,提前谢谢。

2 个答案:

答案 0 :(得分:1)

假设您正在使用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();
    }

}

答案 1 :(得分:0)

您使用json是否简单?如果是,请尝试:

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