2015-06-08 75 views
5

我有以下字符串傳遞給服務器:GSON:不是一個JSON對象

{ 
    "productId": "", 
    "sellPrice": "", 
    "buyPrice": "", 
    "quantity": "", 
    "bodies": [ 
     { 
      "productId": "1", 
      "sellPrice": "5", 
      "buyPrice": "2", 
      "quantity": "5" 
     }, 
     { 
      "productId": "2", 
      "sellPrice": "3", 
      "buyPrice": "1", 
      "quantity": "1" 
     } 
    ] 
} 

這是http://jsonlint.com/

我想要得到的體陣列領域的有效的JSON。

這就是我正在做它:

Gson gson = new Gson(); 
JsonObject object = gson.toJsonTree(value).getAsJsonObject(); 
JsonArray jsonBodies = object.get("bodies").getAsJsonArray(); 

但在我得到異常的第二行如下:

HTTP Status 500 - Not a JSON Object: "{\"productId\":\"\",\"sellPrice\":\"\",\"buyPrice\":\"\",\"quantity\":\"\",\"bodies\":[{\"productId\":\"1\",\"sellPrice\":\"5\",\"buyPrice\":\"2\",\"quantity\":\"5\"},{\"productId\":\"2\",\"sellPrice\":\"3\",\"buyPrice\":\"1\",\"quantity\":\"1\"}]}" 

如何做正確呢?

+1

可能想看看這個http://stackoverflow.com/a/15116323/2044733。第二個選項開始「使用JsonObject」,看起來就像你想要的。 – bbill

回答

4

我已經使用parse方法,如https://stackoverflow.com/a/15116323/2044733之前所述,它的工作。

實際的代碼看起來像

JsonParser jsonParser = new JsonParser(); 
jsonParser.parse(json).getAsJsonObject(); 

the docs它看起來像你正在運行到描述的錯誤在那裏你它認爲你的toJsonTree對象不是正確的類型。在這裏另一個答案,以及相關的線程上提到

上面的代碼等同於

JsonObject jelem = gson.fromJson(json, JsonElement.class); 

+1

是的,您的解決方案適合我! – marknorkin

8

Gson#toJsonTree javadoc指出

該方法序列化指定的對象成其等效 表示作爲JsonElement秒的樹。

即,它基本上

String jsonRepresentation = gson.toJson(someString); 
JsonElement object = gson.fromJson(jsonRepresentation, JsonElement.class); 

一個Java String被轉換爲JSON字符串,即一個JsonPrimitive,而不是JsonObject。換句話說,toJsonTree正在解釋作爲JSON字符串而不是JSON對象傳遞的String值的內容。

您應該直接使用

JsonObject object = gson.fromJson(value, JsonObject.class); 

,轉換您的StringJsonObject

-1

JsonArray jsonBodies = object.getAsJsonArray(「bodies」);

+0

考慮到異常發生在'getAsJsonObject'上會發生什麼變化? –