英文:
Cannot properly parse and display Json
问题
while((inputLine = in.readLine()) != null)
{
jsonData = inputLine;
System.out.println(jsonData);
}
JSONObject object = null;
try {
object = (JSONObject) new JSONParser().parse(jsonData);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject weather = (JSONObject) object.get("weather");
String description = weather.get("description").toString();
System.out.println(description);
in.close();
我附上的代码从第38行开始。我想尝试从我解析的Json中打印出“description”字段。
来自json的相关部分如下:
“weather”:[ { “id”:800, “main”:“晴朗”, “description”:“晴空”, “icon”:“01n” } ],
英文:
while((inputLine = in.readLine()) != null)
{
jsonData = inputLine;
System.out.println(jsonData);
}
JSONObject object = null;
try {
object = (JSONObject) new JSONParser().parse(jsonData);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject weather = (JSONObject) object.get("weather");
String description = weather.get("description").toString();
System.out.println(description);
in.close();
The above code produces the following error:
The code I've attached starts at line 38. I want to try to print out the "description" field from the Json I have parsed.
The relevant part from the json is:
"weather": [ { "id": 800, "main": "Clear", "description": "clear sky", "icon": "01n" } ],
答案1
得分: 1
你正在将一个 JSONArray 解析为 JsonObject,在你的代码中的以下行:
JSONObject weather = (JSONObject) object.get("weather");
weather 是一个 JsonArray
我尝试了以下代码,它对我有效。
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject("{\"weather\": [ { \"id\": 800, \"main\": \"Clear\", \"description\": \"clear sky\", \"icon\": \"01n\" } ]}");
JSONArray weatherArray = jsonObject.getJSONArray("weather");
JSONObject weatherJson = weatherArray.getJSONObject(0);
System.out.println(weatherJson.get("description"));
}
输出
clear sky
英文:
You are Parsing a JSONArray to JsonObject
at below line in ur code
JSONObject weather = (JSONObject) object.get("weather");
weather is a JsonArray
I tried below code it worked for me.
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject("{\"weather\": [ { \"id\": 800, \"main\": \"Clear\", \"description\": \"clear sky\", \"icon\": \"01n\" } ]}");
JSONArray weatherArray = jsonObject.getJSONArray("weather");
JSONObject weatherJson = weatherArray.getJSONObject(0);
System.out.println(weatherJson.get("description"));
}
output
clear sky
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论