I have the following code:
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);
It gives me the following output:
gson.toJson: [{"id":"8a3d16bb328c9ba201328c9ba5db0000","roomID":9411,"numberOfUsers":4,"roomType":"BigTwo"},{"i开发者_JAVA百科d":"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.
Can someone please help me parse my Json string to JsonObject? I have checked in http://jsonlint.com/ that my json is valid though.
It's because due to the JSON structure.. I have to put it into a JSONObject first, like so
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty(ServerConstants.JSONoutput, gson.toJson(roomList));
Then I would deserialize like
List<RoomData> roomList = gson.fromJson(jsonObj.get(CardGameConstants.JSONoutput).toString(), listType);
for (RoomData roomData : roomList) {
System.out.println(roomData.getRoomID());
}
This should give you some basic idea.
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"));
}
The problem with the code is that roomList
is not a JsonObject
as evident in the printed output. It's actually a JsonArray
.
To fix the code, call .getAsJsonArray()
(instead of .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);
精彩评论