作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有 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/
我是一名优秀的程序员,十分优秀!