有时项目中对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串.请看本文是如何处理的吧:
实体类:
- 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 + ", title=" + title
- + "]";
- }
-
- }
注意这里定义了一个TableData实体类:
- import java.util.List;
-
- public class TableData {
-
- private String tableName;
-
- private List tableData;
-
- public String getTableName() {
- return tableName;
- }
-
- public void setTableName(String tableName) {
- this.tableName = tableName;
- }
-
- public List getTableData() {
- return tableData;
- }
-
- public void setTableData(List tableData) {
- this.tableData = tableData;
- }
- }
测试类:
(仔细看将json转回为对象的实现,这里经过两次转化,第一次转回的结果是map不是我们所期望的对象,对map再次转为json后再转为对象,我引用的是Gson2.1的jar处理正常,好像使用Gson1.6的jar会报错,所以建议用最新版本)
输出结果:
- [{"tableName":"students","tableData":[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 10:04:12 PM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 10:04:12 PM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 10:04:12 PM"}]},{"tableName":"teachers","tableData":[{"id":1,"name":"米老师","title":"教授"},{"id":2,"name":"丁老师","title":"讲师"}]}]
- students
- Student [birthDay=Fri Jun 22 22:04:12 CST 2012, id=1, name=李坤]
- Student [birthDay=Fri Jun 22 22:04:12 CST 2012, id=2, name=曹贵生]
- Student [birthDay=Fri Jun 22 22:04:12 CST 2012, id=3, name=柳波]
- teachers
- Teacher [id=1, name=米老师, title=教授]
- Teacher [id=2, name=丁老师, title=讲师]
其实就是多次使用,进行解析。
转自:http://blog.csdn.net/lk_blog/article/details/7685237