Java创建和解析Json数据方法(二)——org.json包的使用

时间:2023-03-08 22:42:37

(二)org.json包的使用

1.简介

  工具包org.json.jar,是一个轻量级的,JAVA下的json构造和解析工具包,它还包含JSON与XML, HTTP headers, Cookies,  CDL的转换。
        这篇学习笔记,主要介绍常用的一些类如:JSONObject、JSONArray、JSONStringer等的一些用法;介绍了如何将Map、Collection、Java Bean等对象转化为json数据;介绍了如何使用org.json包解析json数据等。
        工具包org.json.jar的下载:http://download.****.net/detail/zen99t/9398584

2.常用类

Java创建和解析Json数据方法(二)——org.json包的使用
        各种类的用法可以去官网看说明,很详细:http://www.json.org/java/index.html

3.构造json的示例用法

3.1 JSONObject.java

        官网给出的JSONObject的构造函数如下:
Java创建和解析Json数据方法(二)——org.json包的使用
        比较常用就是传入String、map或者bean来构造JSON对象,代码例子如下:
首先定义一个java bean类:
 package orgjson;

 /**
  * 包含getter和setter的java bean类
  * @author Zen9
  */
 public class Student {
     private String name;
     private String sex;
     private int 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 int getAge() {
         return age;
     }
     public void setAge(int age) {
         this.age = age;
     }
 }
然后测试构造方法;也可以用put方法来向JSON对象中添加key/value对,当用put方法时候,value值可以是int、double、String、、boolean、collection、Map等等,但不可以为bean类型,代码如下:
 package orgjson;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import org.json.*;
 public class JsonTest {
     public static void constructorTest() {

         String jsonStr = "{'name':'JTZen9','age':21}";
         JSONObject strJson = new JSONObject(jsonStr); // 传入字符串
         System.out.println("构造参数为String类:" + strJson);

         Map<string object> map = new HashMap<string object>();
         map.put("age", 21);
         map.put("sex", "male");
         map.put("name", "JTZen9");
         JSONObject mapJson = new JSONObject(map); // 传入Map类型
         System.out.println("构造参数为Map类:" + mapJson);

         Student student = new Student();
         student.setAge(21);
         student.setName("JTZen9");
         student.setSex("male");
         JSONObject beanJson = new JSONObject(student); // 传入Bean类型
         System.out.println("构造参数为Bean类:" + beanJson);
     }

     public static void putMethodTest() {

         JSONObject jsonObject1 = new JSONObject();
         jsonObject1.put("bookName", "JTZen9");
         jsonObject1.put("age", 21);
         System.out.println(jsonObject1);

         JSONObject jsonObject2 = new JSONObject();
         List<object> list = new ArrayList</object><object>();
         for (int i = 1; i < 3; i++) {
             Map<string object=""> map = new HashMap<string object="">();
             map.put("title", "java程序设计 第" + i + "版");
             map.put("price", i*20);
             list.add(map);
         }
         jsonObject2.put("book", list);
         System.out.println(jsonObject2);

         Student student = new Student();
         student.setAge(21);
         student.setName("JTZen9");
         student.setSex("male");
         jsonObject2 = new JSONObject(student);
         JSONObject jsonObject3 = new JSONObject();
         jsonObject3.put("people", jsonObject2);   //不可以直接传bean类对象put("people",student)
         System.out.println(jsonObject3);
     }

     public static void main(String[] args) throws Exception {
         constructorTest();
         System.out.println("---------------------------------------------------------");
         putMethodTest();
     }
 }
输出结果:
Java创建和解析Json数据方法(二)——org.json包的使用

3.2 JSONArray.java

1.构造函数

官网上的JSONObject的构造函数如下:

Java创建和解析Json数据方法(二)——org.json包的使用
        这里用Collection、String和Object型的array作为参数,给出例子如下:
 package orgjson;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import org.json.*;
 public class JsonArrayTest {
     public static void constructorTest() {

         String jsonStr = "[{'name':'JTZen9','age':21}]";
         JSONArray strJson = new JSONArray(jsonStr);     // 传入字符串
         System.out.println("构造参数为String类:" + strJson);

         List<Object> list = new ArrayList<Object>();
         for (int i = 1; i < 3; i++) {
             Map<string object=""> map = new HashMap<string object="">();
             map.put("title", "java程序设计 第" + i + "版");
             map.put("price", i*20);
             list.add(map);
         }
         JSONArray mapJson = new JSONArray(list);         // 传入Collection类型
         System.out.println("构造参数为Collection类:" + mapJson);

         int[] numlist = new int[10];
         for (int i = 0; i < numlist.length; i++) {
             numlist[i] = i;
         }
         JSONArray arrayJson = new JSONArray(numlist);     // 传入Array类型,实例1
         System.out.println(arrayJson);

         Student[] student = {new Student(),new Student()};
         student[0].setAge(21);
         student[0].setName("JTZen9");
         student[0].setSex("male");
         student[1].setAge(21);
         student[1].setName("heiheihei");
         student[1].setSex("female");
         JSONArray beanJson = new JSONArray(student);     // 传入Array类型,实例2
         System.out.println("构造参数为Array类:" + beanJson);
     }

     public static void main(String[] args) {
         constructorTest();
     }
 }
        输出结果如下:
Java创建和解析Json数据方法(二)——org.json包的使用

2.put方法创建

put方法中可以直接将int、double、Collection、Map等加进去,也可以添加下标来指定添加的位置:put(int index, java.util.Map value) ,使用put方法构造的JSON数组,如果传入的是数组,都会自动加一对中括号[ ],那么出来的结果就会有两层的中括号[ ],代码例子如下:

 package orgjson;
 import java.util.HashMap;
 import java.util.Map;
 import org.json.*;
 public class JSONArrayTest {
     public static void putMethodTest() {
         JSONArray jsonArray1 = new JSONArray();
         jsonArray1.put("JTZen9");
         jsonArray1.put(21);
         jsonArray1.put("male");
         System.out.println(jsonArray1);

         JSONArray jsonArray2 = new JSONArray();
         Map<string object=""> map = new HashMap<string object="">();
         map.put("title", "java程序设计 第2版");
         map.put("price", 20);
         jsonArray2.put(map);        //传入一个map
         System.out.println("传入一个Map:" + jsonArray2);
         map.clear();
         map.put("title", "java程序设计 第3版");
         map.put("price", 30);
         jsonArray2.put(map);        //没有下标的直接在结果后面添加
         System.out.println("没有指定下标:" + jsonArray2);
         map.clear();
         map.put("title", "java程序设计 第1版");
         map.put("price", 10);
         jsonArray2.put(0,map);        //使用下标可以添加到自定义的位置
         System.out.println("添加到第一个位置:" + jsonArray2);

         Student[] student = { new Student(), new Student() };
         student[0].setAge(21);
         student[0].setName("JTZen9");
         student[0].setSex("male");
         student[1].setAge(21);
         student[1].setName("heiheihei");
         student[1].setSex("female");
         JSONArray jsonArray3 = new JSONArray();
         jsonArray3.put(student);
         System.out.println("注意输出结果:" + jsonArray3);

     }

     public static void main(String[] args) {
         putMethodTest();
     }
 }
输出的结果如下:
Java创建和解析Json数据方法(二)——org.json包的使用

3.3 JSONStringer.java & JSONWriter.java

        ①JSONWriter可以用来构建一个JSON格式的文本,并转换成String,可以写入文件,便于传输和存储。只有一个构造函数:JSONWriter(java.io.Writer w) 
        ②常用几个函数和说明:
Java创建和解析Json数据方法(二)——org.json包的使用
        ③JSONStringer是JSONWriter的子类;用法跟JSONWriter几乎一样,区别是可以直接new JSONStringer()创建对象,不用传入构造参数。JSONStringer也可以通过object().key().value().key().value().endObject()进行构造;
        下面是简单的写入代码例子:(可以尝试写入更复杂数据)
 package orgjson;
 import java.io.PrintWriter;
 import java.util.HashMap;
 import java.util.Map;
 import org.json.*;
 public class JSONWriterStringerTest {
     public static void JSONStringerTest() throws Exception {

         PrintWriter writer = new PrintWriter("test.txt");
         JSONWriter jsonWriter = new JSONWriter(writer);
         jsonWriter.object().key("name").value("JTZen9").key("age").value(21).key("sex").value("male").endObject();
         writer.flush();
         writer.close();

         Map<string object=""> map1 = new HashMap<string object="">();
         map1.put("age", 21);
         map1.put("sex", "male");
         map1.put("name", "jtzen9");
         Map<string object=""> map2 = new HashMap<string object="">();
         map2.put("age", 21);
         map2.put("sex", "female");
         map2.put("name", "heiheihei");
         JSONStringer jsonStringer = new JSONStringer();
         jsonStringer.array().value(map1).value(map2).endArray();
         System.out.println(jsonStringer);
     }

     public static void main(String[] args) throws Exception {
         JSONStringerTest();
     }
 }
输出结果,上面为test.txt文件,下面为控制台:
Java创建和解析Json数据方法(二)——org.json包的使用

3.4 JSONTokener.java

        JSONTokener读取包含json格式数据的文件,然后可以将JSONTokener对象作为参数来构造JSONObject或JSONArray,然后再进行相应的解析。
以上面的test.txt为例,简单代码示例如下:
 package orgjson;
 import java.io.File;
 import java.io.FileReader;
 import org.json.*;
 public class JSONTokenerTest {

     public static void readJsonFile() throws Exception{
         JSONTokener jsonTokener = new JSONTokener(new FileReader(new File("test.txt")));
         JSONObject jsonObject = new JSONObject(jsonTokener);
         System.out.println(jsonObject);
         System.out.println("姓名:" + jsonObject.getString("name"));
         System.out.println("年龄:" + jsonObject.getInt("age"));
     }

     public static void main(String[] args) throws Exception {
         readJsonFile();
     }
 }
输出结果如下:
Java创建和解析Json数据方法(二)——org.json包的使用

4.解析例子

        这里给出一个相对复杂的json数据:
json.txt
 [
     {
         "institute":{
             "name":"Software Institute",
             "grade":[
                 {
                     "name":"freshman",
                     "class":[
                         {
                             "no.":1,
                             "students":61
                         },
                         {
                             "no.":2,
                             "students":62
                         },
                         {
                             "no.":3,
                             "students":63
                         }
                     ]
                 },
                 {
                     "name":"sophomore",
                     "class":[
                         {
                             "no.":1,
                             "students":51
                         },
                         {
                             "no.":2,
                             "students":52
                         },
                         {
                             "no.":3,
                             "students":53
                         }
                     ]
                 },
                 {
                     "name":"junior",
                     "class":[
                         {
                             "no.":1,
                             "students":41
                         },
                         {
                             "no.":2,
                             "students":42
                         },
                         {
                             "no.":3,
                             "students":43
                         }
                     ]
                 }
             ]
         }
     }
 ]
然后,如果我要获取grade为sophomore的no.等于3的students数量,那么代码如下:
 package orgjson;
 import java.io.File;
 import java.io.FileReader;
 import org.json.JSONArray;
 import org.json.JSONObject;
 import org.json.JSONTokener;
 public class JSONTest {
     public static void main(String[] args) throws Exception {
         JSONTokener jsonTokener = new JSONTokener(new FileReader(new File("json.txt")));
         JSONArray jsonArray = new JSONArray(jsonTokener);//获取整个json文件的内容,因为最外层是数组,所以用JSONArray来构造
         System.out.println(jsonArray);

         //这个JSONArray数组只包含一个JSONObject对象,标为jsonObject1
         JSONObject jsonObject1 = jsonArray.getJSONObject(0);
         System.out.println(jsonObject1); 

         //jsonObject1只包含一个institute字段,这里获取这个字段内容赋给jsonObject2
         JSONObject jsonObject2 = jsonObject1.getJSONObject("institute");
         System.out.println(jsonObject2);

         //jsonObject2包含name字段和grade字段,grade字段对应的是一个JSONArray数组
         String valueOfname = jsonObject2.getString("name");
         System.out.println(valueOfname);
         JSONArray jsonArray2 = jsonObject2.getJSONArray("grade");
         System.out.println(jsonArray2);

         //jsonArray2数组包含3个对象,每个对象里面有name字段和class字段,这里获取第二个对象
         JSONObject jsonObject3 = jsonArray2.getJSONObject(1);
         System.out.println(jsonObject3);

         //然后从jsonObject3对象里获取class字段对应的JSONArray数组
         JSONArray jsonArray3 = jsonObject3.getJSONArray("class");
         System.out.println(jsonArray3);

         //下面直接获取no.等于3的students数量,过程都一样
         int num = jsonArray3.getJSONObject(2).getInt("students");
         System.out.println("最后获取的结果为:" + num);
     }
 }
输出的结果如下,这里只截取控制台输出的前半部分结果:
Java创建和解析Json数据方法(二)——org.json包的使用

5.结束语

之前解析json数据都是一直百度百度,别人怎么用就怎么用,做大作业时有时候会org.json包也导入,Gson包也导入,然后各用一点功能。现在想想其实只用一个org.json包就可以完全解决我的需求,只是之前一直没有总结各种用法,所以这两天看了下官网源码,总结了下学习笔记,还是收获蛮大的。

        其实看官网api文档,然后自己动手实践各种方法才是最好的学习方式。百度别人的教程,有时候只能得到小部分的说明。
        org.json包还有很多的api方法并没有用过,所以就不做笔记了。以后用到再继续完善。

相关文章