将json String转换为Objects数组

时间:2013-08-27 06:40:55

标签: java json gson arrays

我将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)

1 个答案:

答案 0 :(得分:19)

试试这个

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