gson 将json解析为java对象:应为开始_OBJECT,但实际为BEGIN_ARRAY

lh80um4z  于 2022-11-23  发布在  Java
关注(0)|答案(2)|浏览(253)

有人能帮助我解析json字符串对象,我尝试,但总是得到这样的错误:

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 3 path $[0]

下面是我的代码:
项目类别:

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Item{

    @JsonProperty("id")
    String id;
    
    @JsonProperty("dTime")
    long dTime;
    
    @JsonProperty("aTime")
    long aTime;
}

将json转换为对象:

String jsonString = "[
    [
        {
            "id":"string",
            "dTime": 1111111111,
            "aTime": 1111111111
        },
        {
            "id":"string",
            "dTime": 1111111111,
            "aTime": 1111111111
        }
    ]
]";
Gson gson = new Gson();
Type listType = new TypeToken<List<Item>>() {}.getType();
List<Item> list = gson.fromJson(jsonString, listType);

System.out.println(gson.toJson(list));
    • 更新:**因为我从外部API获得了此json作为响应:
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request, String.class);

Is it possible to make this converting to Array of Item objects inside this restTemplate.exchange(..) or this with gson is better way?

h6my8fg2

h6my8fg21#

您可以使用ParameterizedTypeReference直接在java列表对象中进行Map,并使用List<List<Item>>,因为您的数据 Package 在[]

ParameterizedTypeReference<List<List<Item>>> responseType =
                    new ParameterizedTypeReference<List<List<Item>>>() {};
ResponseEntity<List<List<Item>>> response = 
                    restTemplate.exchange(url, HttpMethod.POST, request, responseType);
g52tjvyc

g52tjvyc2#

您的jsonString有一个额外的'['。它应该是

String jsonString = "
[
    {
        "id":"string",
        "dTime": 1111111111,
        "aTime": 1111111111
    },
    {
        "id":"string",
        "dTime": 1111111111,
        "aTime": 1111111111
    }
]
";

相关问题