json : json数据解析(一)

摘要:
项目中经常使用json格式的数据转换和分析。我以前写过一些小例子,但现在我将整理它们以供以后使用,并帮助后来者。言归正传:jar包使用了:json-lib-2.4-jdk15.jar。当然,您也可以使用自己的版本。一般来说,没有问题。

在项目中经常用到json格式的数据转换与解析,先前写过一些小例子,现在整理下,以备后用和帮助后来者。

言归正传:

使用到的jar包 :json-lib-2.4-jdk15.jar,当然你也可以用自己版本的,一般都没啥问题。

一、用于测试数据的类:

1.Student

json : json数据解析(一)第1张json : json数据解析(一)第2张
  1 /*
  2  * To change this template, choose Tools | Templates
  3  * and open the template in the editor.
  4  */
  5 package com.json.gson;
  6 
  7 import java.util.List;
  8 
  9 /**
 10  * gsonTest测试类 : 学生
 11  *
 12  * @author zhengze.su
 13  */
 14 public class Student {
 15 
 16     private String name;
 17     private String sex;
 18     private int age;
 19     private String address;
 20     private List<Hobby> hobbyList;
 21     private List<Course> courseList;
 22 
 23     /**
 24      * @return the name
 25      */
 26     public String getName() {
 27         return name;
 28     }
 29 
 30     /**
 31      * @param name the name to set
 32      */
 33     public void setName(String name) {
 34         this.name = name;
 35     }
 36 
 37     /**
 38      * @return the sex
 39      */
 40     public String getSex() {
 41         return sex;
 42     }
 43 
 44     /**
 45      * @param sex the sex to set
 46      */
 47     public void setSex(String sex) {
 48         this.sex = sex;
 49     }
 50 
 51     /**
 52      * @return the age
 53      */
 54     public int getAge() {
 55         return age;
 56     }
 57 
 58     /**
 59      * @param age the age to set
 60      */
 61     public void setAge(int age) {
 62         this.age = age;
 63     }
 64 
 65     /**
 66      * @return the address
 67      */
 68     public String getAddress() {
 69         return address;
 70     }
 71 
 72     /**
 73      * @param address the address to set
 74      */
 75     public void setAddress(String address) {
 76         this.address = address;
 77     }
 78 
 79     /**
 80      * @return the hobbyList
 81      */
 82     public List<Hobby> getHobbyList() {
 83         return hobbyList;
 84     }
 85 
 86     /**
 87      * @param hobbyList the hobbyList to set
 88      */
 89     public void setHobbyList(List<Hobby> hobbyList) {
 90         this.hobbyList = hobbyList;
 91     }
 92 
 93     /**
 94      * @return the courseList
 95      */
 96     public List<Course> getCourseList() {
 97         return courseList;
 98     }
 99 
100     /**
101      * @param courseList the courseList to set
102      */
103     public void setCourseList(List<Course> courseList) {
104         this.courseList = courseList;
105     }
106 }
View Code

2.Hobby

json : json数据解析(一)第3张json : json数据解析(一)第4张
 1 /*
 2  * To change this template, choose Tools | Templates
 3  * and open the template in the editor.
 4  */
 5 package com.json.gson;
 6 
 7 /**
 8  * gsonTest测试类 : 爱好
 9  *
10  * @author zhengze.su
11  */
12 public class Hobby {
13 
14     private String hobbyName;
15 
16     /**
17      * @return the hobbyName
18      */
19     public String getHobbyName() {
20         return hobbyName;
21     }
22 
23     /**
24      * @param hobbyName the hobbyName to set
25      */
26     public void setHobbyName(String hobbyName) {
27         this.hobbyName = hobbyName;
28     }
29 }
View Code

3.Course

json : json数据解析(一)第5张json : json数据解析(一)第6张
 1 /*
 2  * To change this template, choose Tools | Templates
 3  * and open the template in the editor.
 4  */
 5 package com.json.gson;
 6 
 7 /**
 8  * gsonTest测试类 : 课程
 9  *
10  * @author zhengze.su
11  */
12 public class Course {
13 
14     private String teacherName;
15     private String courseName;
16 
17     /**
18      * @return the teacherName
19      */
20     public String getTeacherName() {
21         return teacherName;
22     }
23 
24     /**
25      * @param teacherName the teacherName to set
26      */
27     public void setTeacherName(String teacherName) {
28         this.teacherName = teacherName;
29     }
30 
31     /**
32      * @return the courseName
33      */
34     public String getCourseName() {
35         return courseName;
36     }
37 
38     /**
39      * @param courseName the courseName to set
40      */
41     public void setCourseName(String courseName) {
42         this.courseName = courseName;
43     }
44 }
View Code

4.Person

json : json数据解析(一)第7张json : json数据解析(一)第8张
 1 /*
 2  * To change this template, choose Tools | Templates
 3  * and open the template in the editor.
 4  */
 5 package com.json.gson;
 6 
 7 /**
 8  *
 9  * @author Administrator
10  */
11 public class Person {
12 
13     private String name;
14     private String age;
15     private String hobby;
16 
17     /**
18      * @return the name
19      */
20     public String getName() {
21         return name;
22     }
23 
24     /**
25      * @param name the name to set
26      */
27     public void setName(String name) {
28         this.name = name;
29     }
30 
31     /**
32      * @return the age
33      */
34     public String getAge() {
35         return age;
36     }
37 
38     /**
39      * @param age the age to set
40      */
41     public void setAge(String age) {
42         this.age = age;
43     }
44 
45     /**
46      * @return the hobby
47      */
48     public String getHobby() {
49         return hobby;
50     }
51 
52     /**
53      * @param hobby the hobby to set
54      */
55     public void setHobby(String hobby) {
56         this.hobby = hobby;
57     }
58 }
View Code

5.模拟获取数据

json : json数据解析(一)第9张json : json数据解析(一)第10张
 1 /*
 2  * To change this template, choose Tools | Templates
 3  * and open the template in the editor.
 4  */
 5 package com.json.gson;
 6 
 7 import java.util.ArrayList;
 8 import java.util.List;
 9 
10 /**
11  * 获取模拟数据
12  *
13  * @author Administrator
14  */
15 public class GetDataUtil {
16 
17     /**
18      * 获取hobbyList
19      *
20      * @return
21      */
22     public List<Hobby> getHobbyList() {
23         List<Hobby> hobbyList = new ArrayList<Hobby>();
24         Hobby hobby = null;
25         for (int i = 0; i <= 2; i++) {
26             hobby = new Hobby();
27             hobby.setHobbyName("爱好(" + i + 1 + ")");
28             hobbyList.add(hobby);
29         }
30 
31         return hobbyList;
32     }
33 
34     /**
35      * 获取courseList
36      *
37      * @return
38      */
39     public List<Course> getCourseList() {
40         List<Course> courseList = new ArrayList<Course>();
41         Course course = null;
42         for (int i = 0; i <= 0; i++) {
43             course = new Course();
44             course.setCourseName("课程" + (i + 1));
45             course.setTeacherName("老师" + (i + 1));
46             courseList.add(course);
47         }
48 
49         return courseList;
50     }
51 
52     public List<Student> getStudentList() {
53 
54         List<Student> studentList = new ArrayList<Student>();
55         List<Hobby> hobbyList = this.getHobbyList();
56         List<Course> courseList = this.getCourseList();
57         Student student = null;
58         for (int i = 0; i <= 0; i++) {
59             student = new Student();
60             student.setName("学生" + (i + 1));
61             if (i % 2 == 0) {
62                 student.setSex("男");
63             } else {
64                 student.setSex("女");
65             }
66             student.setAge(i + 10);
67             student.setHobbyList(hobbyList);
68             student.setCourseList(courseList);
69             studentList.add(student);
70         }
71 
72         return studentList;
73 
74     }
75 }
View Code

二、gsonTest测试类 : 方法类

json : json数据解析(一)第11张json : json数据解析(一)第12张
  1 /*
  2  * To change this template, choose Tools | Templates
  3  * and open the template in the editor.
  4  */
  5 package com.json.gson;
  6 
  7 import java.util.ArrayList;
  8 import java.util.Iterator;
  9 import java.util.List;
 10 import net.sf.json.JSONArray;
 11 import net.sf.json.JSONObject;
 12 import net.sf.json.JSONSerializer;
 13 import net.sf.json.JsonConfig;
 14 
 15 /**
 16  * gsonTest测试类 : 方法类
 17  *
 18  * @author zhengze.su
 19  */
 20 public class GsonTest001 {
 21 
 22 //    //获取模拟数据
 23 //    public void getData() {
 24 //        GetDataUtil dataUtil = new GetDataUtil();
 25 //        List<Student> studentList = dataUtil.getStudentList();
 26 //        System.out.println("studentList.size():"+studentList.size());
 27 //    }
 28     
 29     //1. list对象转换成json字符串
 30     // 备注 :此处只是将 student 对象转换成了 json字符串,后面将利用此处的数据,将其转换为对应的对象
 31     public void studentListToJson() {
 32         GetDataUtil dataUtil = new GetDataUtil();
 33         List<Student> studentList = dataUtil.getStudentList();
 34         JSONArray jsonArray = JSONArray.fromObject(studentList);
 35         System.out.println(jsonArray);
 36     }
 37 
 38     //2. json字符串转list输出,类型为 String
 39     public void jsonStrToList() {
 40         String jsonStr = "["aa1","bb2","cc3","dd4"]";
 41         JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(jsonStr);
 42         System.out.println("出来吧,皮卡丘:" + jsonArray);
 43         List<String> strList = (List) JSONSerializer.toJava(jsonArray);
 44         for (String s : strList) {
 45             System.out.println("打印出来看一看吆:" + s);
 46         }
 47     }
 48 
 49     //////// json 字符串 转为 对象,例子比较简单,主要是区分一下不同的形式
 50     /////// 关于此处提到了 JsonConfig() ,后面再写个关于其配置的小例子
 51     //3. json字符串转对象,以 person类为例
 52     public void testJsonList1() { // 1
 53         String json = "[{'name':'ml','age':'24','hobby':'eat'},{'name':'aarn','age':'25','hobby':'play'},{'name':'su','age':'xx','hobby':'study'}]";
 54         JSONArray jsonarray = JSONArray.fromObject(json);
 55         System.out.println(jsonarray);
 56         List list = (List) JSONArray.toCollection(jsonarray, Person.class);//person类
 57         Iterator ite = list.iterator();
 58         while (ite.hasNext()) {
 59             Person pp = (Person) ite.next();
 60             System.out.println(pp.getName());
 61         }
 62     }
 63 
 64     //4. json字符串转对象,以 person类为例
 65     public void testJsonList2() {  //2 
 66         String json = "[{'name':'ml','age':'24','hobby':'eat'},{'name':'aarn','age':'25','hobby':'play'},{'name':'su','age':'xx','hobby':'study'}]";
 67         JSONArray jsonarray = JSONArray.fromObject(json);
 68         System.out.println(jsonarray);
 69         List list = (List) JSONArray.toList(jsonarray, Person.class);
 70         Iterator iter = list.iterator();
 71         while (iter.hasNext()) {
 72             Person ppp = (Person) iter.next();
 73             System.out.println(ppp.getHobby());
 74         }
 75     }
 76 
 77     //5. json字符串转对象,以 person类为例
 78     public void testJsonList3() { //3
 79         String json = "[{'name':'ml','age':'24','hobby':'eat'},{'name':'aarn','age':'25','hobby':'play'},{'name':'su','age':'xx','hobby':'study'}]";
 80         JSONArray jsonarray = JSONArray.fromObject(json);
 81         System.out.println(jsonarray);
 82         List list = JSONArray.toList(jsonarray, new Person(), new JsonConfig());
 83         Iterator itera = list.iterator();
 84         while (itera.hasNext()) {
 85             Person pe = (Person) itera.next();
 86             System.out.println(pe.getAge());
 87         }
 88     }
 89 
 90     //6. json字符串转对象,以 person类为例
 91     public void testJsonList4() { // 4
 92         String json = "[{'name':'su','age':'25','hobby':'play'},{'name':'wa','age':'24','hobby':'eat'},{'name':'s','age':'aa','hobby':'mm'}]";
 93         JSONArray jsonarray = (JSONArray) JSONSerializer.toJSON(json);
 94         System.out.println(jsonarray);
 95         List list = (List) JSONSerializer.toJava(jsonarray);
 96         for (Object obj : list) {
 97             JSONObject jbj = JSONObject.fromObject(obj);
 98             Person p = (Person) JSONObject.toBean(jbj, Person.class);
 99             System.out.println(p.getName());
100         }
101     }
102 
103     //7. json字符串转对象,以 person类为例
104     public void testJsonList5() { // 5
105         String json = "[{'name':'su','age':'25','hobby':'play'},{'name':'wa','age':'24','hobby':'eat'},{'name':'s','age':'aa','hobby':'mm'}]";
106         JSONArray jsonarray = (JSONArray) JSONSerializer.toJSON(json);
107         System.out.println(jsonarray);
108         List list = (List) JSONSerializer.toJava(jsonarray);
109         Iterator ite = list.iterator();
110         while (ite.hasNext()) {
111             JSONObject jsonObject = JSONObject.fromObject(ite.next());
112             Person pp = (Person) JSONObject.toBean(jsonObject, Person.class);
113             System.out.println(pp.getName());
114         }
115     }
116 
117     public static void main(String[] args) {
118         GsonTest001 gsonTest001 = new GsonTest001();
119 //        gsonTest001.getData();
120 //        gsonTest001.studentListToJson();
121 //        gsonTest001.jsonStrToList();
122 //        gsonTest001.testJsonList1();
123 //        gsonTest001.testJsonList2();
124 //        gsonTest001.testJsonList3();
125 //        gsonTest001.testJsonList4();
126 //        gsonTest001.testJsonList5();
127 
128 
129 
130     }
131 }
View Code

下一篇将代码注释中提到的未完成的部分,包括解析 对象存在多个属性(包含集合属性)、jsonConfig()的简单使用、某个童鞋给的一份json数据的情况(据说是挺复杂的),在后面的文章中一一分享给大家。

免责声明:文章转载自《json : json数据解析(一)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇如何:从代码创建 UML 类图(ZZ)Sword redis存取二进制数据下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

将对象放入到map中,找出map中指定的某个属性值并放在一个list中

package facadeTest.mapAndObject; import java.util.ArrayList; import java.util.List; /** * * 将对象放入到map中,找出map中指定的某个属性值并放在一个list中 */ public class TargetAndMapChange { public...

搭建第一个web项目:实现用户的增删改查(四)

前台采用了easyUI框架。 这里浪费时间比较多的就是对easyUI中的一些插件的扩展。因为自己一开始jQuery基础确实不是太好,有些问题不能及时发现。 下面是easyUI一个增删改的列表实现: 在图中,可以看到列表底部有总记录,页码,还有reload按钮和添加按钮。所以在项目中建立了一个工具类,用于包装这些数据。EasyGridAction.java...

Windows PowerShell初体验——.NET对象支持

我个人很少用到Linux/Unix 操作系统. 对于不少Linux/Unix管理员在系统任务操作Shell一直保持很难理解. 后来从朋友公司听说他们测试队伍中专门保留了一个脚本Scirpt Shell 测试小组. 我一时更纳闷了. 当然这个问题知道我碰到Windows PowerShell-Windows出的一套Shell工具后 才渐渐理解. Window...

三步轻松打造微信聊天机器人(附源码)

    最近微信公众平台开发是热门,我也跟风做了一个陪聊的公众号。       其实类似的自动回话程序早就有了,比如前一阵很火的小黄鸡(还是小黄鸭来着?)。但尽管是跟风,也要体现一些不同。别人做的都是中文陪聊,咱就来做个英语陪聊。       不管是中文还是英文,做起来都一样,都是利用网络上的接口。或者你也可以试着自己开发一个陪聊程序。       随便在...

限制IP注册到Eureka

平时总有人无意中把自己本地的服务注册到开发、测试环境的注册中心,导致服务器不可用的问题,通过下面的方法禁止不被允许的IP注册到Eureka importjava.util.List; importcom.netflix.eureka.lease.Lease; importorg.slf4j.Logger; importorg.slf4j.LoggerFa...

并发编程(十二)—— Java 线程池 实现原理与源码深度解析 之 submit 方法 (二)

在上一篇《并发编程(十一)—— Java 线程池 实现原理与源码深度解析(一)》中提到了线程池ThreadPoolExecutor的原理以及它的execute方法。这篇文章是接着上一篇文章写的,如果你没有阅读上一篇文章,建议你去读读。本文解析ThreadPoolExecutor#submit。 对于一个任务的执行有时我们不需要它返回结果,但是有我们需要它的...