2016-10-14 153 views
-2

如何將此JSON映射到對象?將JSON數組映射到Java POJO

{"d":"[{\"Key\":\"3\",\"ExternalKey\":\"143234A\",\"Name\":\"cup of juice\",\"Litres\":\"2 litres\",\"Date\":\"2016-10-06T08:32:27\",\"Capacity\":5.4900,\"CapacityType\":\"%\"}, {\"Key\":\"3\",\"ExternalKey\":\"143234A\",\"Name\":\"cup of milk\",\"Litres\":\"2.4 litres\",\"Date\":\"2016-10-06T08:32:27\",\"Capacity\":1667.6100,\"CapacityType\":\"M\"}]"} 

我用一個HashMap嘗試,但它只是把「d」的字符串,其餘作爲一個String對象有一個元素

+0

定義一個類相匹配的JSON結構 – sidgate

+0

我有,還是沒有映射它正常 – Nickmccomb

+0

它給了我這個錯誤:com.fasterxml.jackson.databind.JsonMappingException:在[來源無法反序列化的java.util.ArrayList實例出來VALUE_STRING令牌: { 「d」: 「[{\」 主要\ 「:\」 3 \」 ......等 – Nickmccomb

回答

0

你的JSON字符串有一些額外的「字符。

這是最後的JSON:

{ 
    "d": [ 
    { 
     "Key": "3", 
     "ExternalKey": "143234A", 
     "Name": "cup of juice", 
     "Litres": "2 litres", 
     "Date": "2016-10-06T08:32:27", 
     "Capacity": 5.49, 
     "CapacityType": "%" 
    }, 
    { 
     "Key": "3", 
     "ExternalKey": "143234A", 
     "Name": "cup of milk", 
     "Litres": "2.4 litres", 
     "Date": "2016-10-06T08:32:27", 
     "Capacity": 1667.61, 
     "CapacityType": "M" 
    } 
    ] 
} 

現在,您可以複製JSON和粘貼here得到POJO

+0

我已經做了,但它給了我這個錯誤: com.fasterxml.jackson.databind.JsonMappingException :不能d eserialize java.util.ArrayList的實例在VALUE_STRING標記 以外[來源:{「d」:「[{\」Key \「:\」3 \「...... etc – Nickmccomb

+0

正如我所說的你有一些額外「在你的JSON字符串中,這意味着那些額外的」不應該在那裏使它工作。我希望你能理解 –

+0

你好Nongthonbam,我看不到額外的「在哪裏,他們似乎是在正確的地方(例如,所有的值都是字符串,除了容量,所以它們被包含在」。 「? – Nickmccomb

0

這是一個非常常見的問題,稱爲數據編組。在Java中,傑克遜是最好的解決方案。閱讀本教程:http://wiki.fasterxml.com/JacksonInFiveMinutes

+0

我試過傑克遜和Gson,都其中沒有正確映射它 – Nickmccomb

+0

它給了我這個錯誤:com.fasterxml.jackson.databind.JsonMappingException:無法反序列化java.util.ArrayList的實例從VALUE_STRING標記在[Source:{「d」:「[[ {\「Key \」:\「3 \」...... etc – Nickmccomb

+0

如果我將「d」鍵子串出來並將其映射爲JSON數組,它必須是現在的解決方案。 .. – Nickmccomb

0
 
There are n numbers of libraries available for parsing the JSON and convert into in java classes. 

Some of the examples are, 

GSON 
Jackson 
Logan Square 
Moshi, etc 

You need to create a java class which map with your JSON Response and need to change your pojo according to parsing library. 

For Example, 

Using Logan Square you must annotate your POJO class to @JsonObject and all properties must be annotated with @JsonField. 

Now, you can parse your json using method 

... 
LoganSquare.parse(jsonString, pojoClassName); 
... 

Hopefully this will help you. 

Cheers 
+0

嗨艾米特,不知道如果你在評論之前閱讀上面的帖子,但我已經試過這個,它確實不適用於此JSON響應 – Nickmccomb

0

如果我串了「d」鍵,並將其映射爲一個JSON陣列它的工作原理,即必須是現在的解決方案...