java - 解析 JSON 时,出现奇怪的异常::This is not a JSON Array

标签 java json exception

我遇到了 JSON 解析器的问题。 这是来自服务器的 JSON 响应。

{
 "coord"  : {"lon":37.62,"lat":55.75},
 "weather":[{"id":803,"main":"Clouds","description":"test","icon":"04d"}],
 "base"   :"stations",
 "main"   :{"temp":12.76,"pressure":1007,"humidity":93,"tempmin":12,"tempmax":14},
 "visibility":6000,
 "wind"   :{"speed":4,"deg":300},
 "clouds" :{"all":75},
 "dt":1504881000,
 "sys"    :{"type":1,"id":7325,"message":0.0064,"country":"RU","sunrise":1504838942,"sunset":1504886617},
 "id"     :524901,
 "name"   :"City",
 "cod"    :200
 }

还有java代码......

import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.*;

public static void main(String[] args) throws JSONException {
try {
JsonParser parser = new JsonParser();
JsonObject json = parser.parse("JSON responce here").getAsJsonObject();
JsonArray weather = json.get("weather").getAsJsonArray(); //no problem
int visibility = json.get("visibility").getAsInt();
int id = json.get("id").getAsInt();
int dt = json.get("dt").getAsInt();
String name = json.get("name").getAsString(); 
JsonArray clouds = json.get("clouds").getAsJsonArray(); //here is the problem
JsonArray main = json.get("main").getAsJsonArray(); //here is the problem
} catch (Exception e) {
        e.printStackTrace();
    }
}

问题是......当我编译时,我在 JsonArrayclouds = json.get("clouds"上得到 java.lang.IllegalStateException: This is not a JSON Array. ).getAsJsonArray(); 以及其他类似这样的行。

但是JsonArray天气 = json.get("weather").getAsJsonArray(); 没问题...

我不明白发生了什么......但是数组“天气”节点没有问题......完全没有问题。请帮帮我...出了什么问题?

最佳答案

因为它是一个Json对象

JsonObject json = json.get("clouds").getAsJsonObject()

它会起作用...

或者您可以更改下面给出的数据

{
 "coord"  : {"lon":37.62,"lat":55.75},
 "weather":{"id":803,"main":"Clouds","description":"test","icon":"04d"},
 "base"   :"stations",
 "main"   :{"temp":12.76,"pressure":1007,"humidity":93,"tempmin":12,"tempmax":14},
 "visibility":6000,
 "wind"   :{"speed":4,"deg":300},
 "clouds" :[{"all":75}],
 "dt":1504881000,
 "sys"    :{"type":1,"id":7325,"message":0.0064,"country":"RU","sunrise":1504838942,"sunset":1504886617},
 "id"     :524901,
 "name"   :"City",
 "cod"    :200
 }

关于java - 解析 JSON 时,出现奇怪的异常::This is not a JSON Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46122678/

相关文章:

java - 如何使用 JUnit 5 模拟 Spring 依赖关系?

php - 将 JSON 数据存储为平面文件或数据库

c# - 从我的服务中将异常抛回给客户是否可以?

java - INVOKESTATIC 操作是否会反转堆栈顺序?

Java Struts 1 : forward from action to action. 通过 ActionForms 传递数据

javascript - 如何将 JavaScript 数组转换为 JSON 行的名称/值对中的 'name'?

java - 替换 Arraylist 中的空值

java - 在接口(interface)方法的 throws 子句中放什么?

java - 请问如何将此 Curl 请求移植到 Android?

WCF BodyStyle WrappedRequest 不适用于传入的 JSON 参数?