簡體   English   中英

使用GSON將String解析為JsonObject會產生IllegalStateException:這不是JSON對象

[英]Parsing String to JsonObject using GSON gives IllegalStateException: This is not a JSON Object

我有以下代碼:

JsonParser parser = new JsonParser();
System.out.println("gson.toJson: "  + gson.toJson(roomList));
JsonObject json2 = parser.parse("{\"b\":\"c\"}").getAsJsonObject();
System.out.println("json2: " + json2);
JsonObject json = parser.parse(gson.toJson(roomList)).getAsJsonObject();
System.out.println("json: " + json);

它給了我以下輸出:

gson.toJson: [{"id":"8a3d16bb328c9ba201328c9ba5db0000","roomID":9411,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328b9f3a01328b9f3bb80000","roomID":1309,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328ba09101328ba09edd0000","roomID":1304,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bb8af640000","roomID":4383,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd271fe0001","roomID":5000,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd2e0e30002","roomID":2485,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd3087b0003","roomID":6175,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd35a840004","roomID":3750,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd366250005","roomID":370,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd3807d0006","roomID":9477,"numberOfUsers":4,"roomType":"BigTwo"}]
json2: {"b":"c"}
java.lang.IllegalStateException: This is not a JSON Object.

有人可以幫我解析我的Json字符串到JsonObject嗎? 我已經在http://jsonlint.com/檢查過我的json是有效的。

這是因為由於JSON結構......我必須首先將它放入JSONObject中,就像這樣

JsonObject jsonObj = new JsonObject();
jsonObj.addProperty(ServerConstants.JSONoutput, gson.toJson(roomList));

然后我會反序列化

 List<RoomData> roomList = gson.fromJson(jsonObj.get(CardGameConstants.JSONoutput).toString(), listType);
            for (RoomData roomData : roomList) {
                System.out.println(roomData.getRoomID());
            }

代碼的問題是roomList不是JsonObject ,在打印輸出中很明顯。 它實際上是一個JsonArray

要修復代碼,請調用.getAsJsonArray() (而不是.getAsJsonObject()

JsonParser parser = new JsonParser();
System.out.println("gson.toJson: "  + gson.toJson(roomList));
JsonObject json2 = parser.parse("{\"b\":\"c\"}").getAsJsonObject();
System.out.println("json2: " + json2);
JsonArray json = parser.parse(gson.toJson(roomList)).getAsJsonArray();
System.out.println("json: " + json);

這應該給你一些基本的想法。

ArrayList<String> roomTypes = new ArrayList<String>();

JSONArray jsonArray = new JSONArray(jsonString);

for(int i =0; i<jsonArray.length(); i++){
    roomTypes.add(jsonArray.getJSONObject(i).getString("roomType"));
}

暫無
暫無

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

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