gson 将json字符串转换为对象数组

n8ghc7c1  于 2022-11-06  发布在  其他
关注(0)|答案(2)|浏览(217)

我有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)
xpcnnkqh

xpcnnkqh1#

试试这个

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

esbemjvw2#

使用Jackson'sObjectMapper类,可以读取值并将其Map到对象或对象数组。

final ObjectMapper objectMapper = new ObjectMapper();
Address [] mdls = objectMapper.readValue(addressJson, Address [].class);

对于List<Address>,请用途:

List<Address> mdls = objectMapper.readValue(addressJson, new TypeReference<List<Address>>() {});

相关问题