2011-09-22 83 views
3

解析字符串到JSONObject的我有以下代碼:爪哇 - 使用GSON

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是有效的。非常感謝:)

編輯:

我終於有answer..it的,因爲由於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()); 
      } 

回答

0

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

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")); 
} 
+2

你似乎使用json-simple而不是gson,JSONArray上的String構造函數在gson中無效 – teejay