在解析JSON时,会发生奇怪的异常:这不是JSON数组

时间:2017-09-08 18:36:56

标签: 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();
    }
}

问题是......当我编译时,我有 java.lang.IllegalStateException:这不是JSON数组。 JsonArray clouds = json.get(“clouds” ).getAsJsonArray(); 和其他类似的行。

JsonArray weather = json.get(“weather”)。getAsJsonArray(); 没问题......

我不明白发生了什么......但阵列“天气”节点完全没有问题。拜托,帮帮我......怎么了?

1 个答案:

答案 0 :(得分:3)

因为它是一个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
 }