2013-08-27 132 views
3

的陣列我有JSON數組作爲字符串轉換JSON字符串到對象

[ 
     { 
     "id":"1", 
      "lat": "23.053", 
      "long": "72.629", 
      "location": "ABC", 
      "address": "DEF", 
      "city": "Ahmedabad", 
      "state": "Gujrat", 
      "phonenumber": "1234567" 
     }, 
     { 
     "id":"2", 
      "lat": "23.053", 
      "long": "72.629", 
      "location": "ABC", 
      "address": "DEF", 
      "city": "Ahmedabad", 
      "state": "Gujrat", 
      "phonenumber": "1234567" 
     }, 
     { 
      "id":"3", 
     "lat": "23.053", 
      "long": "72.629", 
      "location": "ABC", 
      "address": "DEF", 
      "city": "Ahmedabad", 
      "state": "Gujrat", 
      "phonenumber": "1234567" 
     }, 
     { 
      "id":"4", 
     "lat": "23.053", 
      "long": "72.629", 
      "location": "ABC", 
      "address": "DEF", 
      "city": "Ahmedabad", 
      "state": "Gujrat", 
      "phonenumber": "1234567" 
     }, 
     { 
      "id":"5", 
     "lat": "23.053", 
      "long": "72.629", 
      "location": "ABC", 
      "address": "DEF", 
      "city": "Ahmedabad", 
      "state": "Gujrat", 
      "phonenumber": "1234567" 
     } 
] 

我想這個字符串轉換爲每個JSON對象。我有一個班級地址。我怎麼會這個JSON字符串轉換爲 對象

我試圖

Address address = gson.fromJson(addressJson, Address.class); 

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 
    com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176) 
    com.google.gson.Gson.fromJson(Gson.java:803) 
    com.google.gson.Gson.fromJson(Gson.java:768) 
    com.google.gson.Gson.fromJson(Gson.java:717) 
    com.google.gson.Gson.fromJson(Gson.java:689) 
+0

http://stackoverflow.com/questions/11503688/rest-and-的可能重複json-conversion-string-to-json-array – muthu

+0

@muthu不,那不是Gson。 – Brian

回答

16

試試這個

Address[] address = gson.fromJson(addressJson, Address[].class); 
+3

+1。另外,如果一個集合比List更受歡迎,你可以在''Arrays.asList''中包裝'fromJson'調用(http://docs.oracle.com/javase/7/docs/api/java/util /Arrays.html#asList(T ...)) – Brian

+0

@Brian這是事實。感謝您指出這一點 –

+0

它正在工作,但同樣的事情,我有一個字段的日期與價值'星期二8月27日星期二06:07:32 UTC 2013'。它說錯誤在java.text.ParseException:Unparseable日期:「Tue Aug 27 11:37:32 IST 2013」​​ \t java.text.DateFormat.parse(DateFormat.java:337)' – jackyesind