亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

解析 json 錯誤:java.lang.IllegalStateException

解析 json 錯誤:java.lang.IllegalStateException

繁星點點滴滴 2022-07-20 20:56:32
我正在嘗試解析一個包含一堆城市的大型 json 文件(以下是文件中的前兩個城市):  [  {    "id": 707860,    "name": "Hurzuf",    "country": "UA",    "coord": {      "lon": 34.283333,      "lat": 44.549999    }  },  {    "id": 519188,    "name": "Novinki",    "country": "RU",    "coord": {      "lon": 37.666668,      "lat": 55.683334    }  } ]我想獲取“名稱”值與字符串匹配的城市的 ID:    JsonParser parser = new JsonParser();    JsonElement jsontree = parser.parse(new FileReader("C:/Users/kevin/Eclipse-workspace-new/kevinzhou_CSCI201_assignment3/WebContent/city.list.json"));    JsonElement je = jsontree.getAsJsonObject();    JsonArray ja = je.getAsJsonArray();    for (Object o : ja)    {        JsonObject city = (JsonObject) o;        if(cityName == city.get("name").getAsString())        {            System.out.println(city.get("id").getAsString());        }    }但是,我收到以下錯誤:java.lang.IllegalStateException: Not a JSON Object: 然后它在冒號后吐出整個文件。
查看完整描述

2 回答

?
慕容708150

TA貢獻1831條經驗 獲得超4個贊

改成


// JsonElement je = jsontree.getAsJsonObject();

JsonArray ja = jsontree.getAsJsonArray();

因為它在頂層包含一個數組


查看完整回答
反對 回復 2022-07-20
?
郎朗坤

TA貢獻1921條經驗 獲得超9個贊

嘗試下面給定的代碼來處理這兩種情況


if (jsontree instanceof JsonObject) {

    JsonObject  jobject = new JsonObject(jsontree .getAsJsonObject());

 } else if (jsontree instanceof JsonArray) {

    JsonArray  jarray =  new JsonArray(jsontree .getAsJsonArray());

 }


查看完整回答
反對 回復 2022-07-20
  • 2 回答
  • 0 關注
  • 244 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號