对List和map等结构的常用转换操作基本上可以满足我们处理的绝大多数需求,但有时项目中对json有特殊的格式规定.比如下面的json串解析:
[{"tableName":"students","tableData":[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 9:54:49 PM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 9:54:49 PM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 9:54:49 PM"}]},{"tableName":"teachers","tableData":[{"id":1,"name":"米老师","title":"教授"},{"id":2,"name":"丁老师","title":"讲师"}]}]
分析之后我们发现普通的方式都不好处理上面的json串.请看本文是如何处理的吧:
实体类:
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
import java.util.Date; public class Student { private int id; private String name; private Date birthDay; public int getId() { return id; } public void setId( int id) { this .id = id; } public String getName() { return name; } public void setName(String name) { this .name = name; } public Date getBirthDay() { return birthDay; } public void setBirthDay(Date birthDay) { this .birthDay = birthDay; } @Override public String toString() { return "Student [birthDay=" + birthDay + ", id=" + id + ", name=" + name + "]" ; } } public class Teacher { private int id; private String name; private String title; public int getId() { return id; } public void setId( int id) { this .id = id; } public String getName() { return name; } public void setName(String name) { this .name = name; } public String getTitle() { return title; } public void setTitle(String title) { this .title = title; } @Override public String toString() { return "Teacher [id=" + id + ", name=" + name + ", id="codetool">
注意这里定义了一个TableData实体类:
测试类:
输出结果:
|