gpt4 book ai didi

java - 如何将 JSON 字符串转换为对象的数组列表

转载 作者:行者123 更新时间:2023-11-29 08:28:27 25 4
gpt4 key购买 nike

我有 JSON 字符串,从 HTTP 请求接收:

     [  
{
"id":15,
"title":"1",
"description":"desc",
"user_id":152
},
{
"id":18,
"title":"2",
"description":"desc",
"user_id":152
},
{
"id":19,
"title":"tab3",
"description":"zadanka",
"user_id":152
}
]

如何将其转换为对象的 ArrayList?

最佳答案

使用 Gson

Gson gson = new Gson();
ArrayList<Object> listFromGson = gson.fromJson("json string",
new TypeToken<ArrayList<Object>>() {}.getType());

使用 jackson

    ObjectMapper mapper = new ObjectMapper();
ArrayList<Object> listFromJackson = mapper.readValue("json string",
new TypeReference<ArrayList<Object>>(){});

如果你可以将一个 pojo 定义为

public class Example {

private Integer id;
private String title;
private String description;
private Integer userId;
// setters / getters
}

然后

ArrayList<Example> listFromGson = gson.fromJson("json string",
new TypeToken<ArrayList<Example>>() {}.getType());

ArrayList<Example> listFromJackson = mapper.readValue("json string",
new TypeReference<ArrayList<Example>>(){});

此外,您应该更喜欢使用 List 而不是 ArrayList

关于java - 如何将 JSON 字符串转换为对象的数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50370859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com