无法正确解析和显示Json

huangapple go评论94阅读模式
英文:

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();

以上代码产生了以下错误:
无法正确解析和显示Json

我附上的代码从第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:
无法正确解析和显示Json

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

huangapple
  • 本文由 发表于 2020年9月30日 14:29:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/64132026.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定