我是靠谱客的博主 潇洒苗条,这篇文章主要介绍java中使用jackson处理json,现在分享给大家,希望可以做个参考。

java实体类 Student.java

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.List; public class Student { private int age; private String name; private String sex; private List<Integer> scores; public Student() { } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public List<Integer> getScores() { return scores; } public void setScores(List<Integer> scores) { this.scores = scores; } }

测试代码 JsonTest.java

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public static void main(String[] args) throws IOException { ObjectMapper om=new ObjectMapper(); Student student=new Student(); student.setAge(10); student.setName("张三"); student.setSex("男"); student.setScores(Arrays.asList(10,20,30)); //讲JavaBean 转换为一个json对象 String studentJson = om.writeValueAsString(student); System.out.println(studentJson); System.out.println("----------我是一条分割线----------"); //将一个json对象转换为JavaBean Student student1= om.readValue(studentJson,Student.class); System.out.println(student1.getName()); System.out.println(student1.getAge()); System.out.println(student1.getScores()); System.out.println("----------我是一条分割线----------"); //获取json的数据 JsonNode jd= om.readTree(studentJson); System.out.println(jd.get("name").asText()); System.out.println(jd.get("age")); System.out.println(jd.get("scores")); System.out.println("----------我是一条分割线----------"); String path = JsonTest.class.getClassLoader().getResource("student.json").getPath(); File fileJson=new File(path); List<Student> list=om.readValue(fileJson, new TypeReference<List<Student>>(){}); for (Student student2: list) { System.out.println(student2.getAge()); System.out.println(student2.getName()); System.out.println(student2.getScores()); } }

student.json文件

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[ { "age": 15, "name": "张三", "sex": "男", "scores":[10,80,90] }, { "age": 16, "name": "李四", "sex": "女", "scores":[100,99,88] } ]

 

最后

以上就是潇洒苗条最近收集整理的关于java中使用jackson处理json的全部内容,更多相关java中使用jackson处理json内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(81)

评论列表共有 0 条评论

立即
投稿
返回
顶部