簡體   English   中英

解析JSON時,會發生奇怪的異常,因為:這不是JSON數組

[英]While parsing a JSON, strange exception occurs as :This is not a JSON Array

我有一個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== json.get(“ clouds”)。getAsJsonArray(); 和其他這樣的行。

但是JsonArray weather = 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
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM