首页 > 代码库 > Java-json系列(二):用JSONObject解析和处理json数据

Java-json系列(二):用JSONObject解析和处理json数据

本文中主要介绍JSONObject处理json数据时候的一些常用场景和方法。

(一)jar包下载

所需jar包打包下载百度网盘地址:https://pan.baidu.com/s/1c27Uyre

 

(二)常见场景及处理方法

1、解析简单的json字符串:

1      // 简单的json测试字符串
2         public static final String JSON_SIMPLE = "{‘name‘:‘tom‘,‘age‘:16}";
3         
4         JSONObject obj = JSONObject.fromObject(JSON_SIMPLE);
5         System.out.println("name is : " + obj.get("name"));
6         System.out.println("age is : " + obj.get("age"));

输出:

name is : tom
age is : 16

 

2、解析嵌套的json字符串:

1      // 嵌套的json字符串
2         public static final String JSON_MULTI = "{‘name‘:‘tom‘,‘score‘:{‘Math‘:98,‘English‘:90}}";
3         JSONObject obj = JSONObject.fromObject(JSON_MULTI);
4         System.out.println("name is : " + obj.get("name"));
5         System.out.println("score is : " + obj.get("score"));
6 
7         JSONObject scoreObj = (JSONObject) obj.get("score");
8         System.out.println("Math score is : " + scoreObj.get("Math"));
9         System.out.println("English score is : " + scoreObj.get("English"));

输出:

name is : tom
score is : {"English":90,"Math":98}
Math score is : 98
English score is : 90

 

3、把bean对象转化成JSONObject对象:

Person、Info、Score类分别如下:(注:要定义成独立的三个public类,不能定义成内部类或非public类,否则会转换异常)

 1 public class Person {
 2     private String name;
 3 
 4     private Info info;
 5 
 6     public String getName() {
 7         return name;
 8     }
 9 
10     public void setName(String name) {
11         this.name = name;
12     }
13 
14     public Info getInfo() {
15         return info;
16     }
17 
18     public void setInfo(Info info) {
19         this.info = info;
20     }
21 
22     @Override
23     public String toString() {
24         return "Person [name=" + name + ", info=" + info + "]";
25     }
26 
27 }
 1 public class Info {
 2     private int age;
 3     private Score score;
 4 
 5     public int getAge() {
 6         return age;
 7     }
 8 
 9     public void setAge(int age) {
10         this.age = age;
11     }
12 
13     public Score getScore() {
14         return score;
15     }
16 
17     public void setScore(Score score) {
18         this.score = score;
19     }
20 
21     @Override
22     public String toString() {
23         return "Info [age=" + age + ", score=" + score + "]";
24     }
25 
26 }
 1 public class Score {
 2     private String math;
 3     private String english;
 4 
 5     public String getMath() {
 6         return math;
 7     }
 8 
 9     public void setMath(String math) {
10         this.math = math;
11     }
12 
13     public String getEnglish() {
14         return english;
15     }
16 
17     public void setEnglish(String english) {
18         this.english = english;
19     }
20 
21     @Override
22     public String toString() {
23         return "Score [math=" + math + ", english=" + english + "]";
24     }
25 
26 }

转换方法:

 1         Score score = new Score();
 2         score.setEnglish("A");
 3         score.setMath("B");
 4 
 5         Info info = new Info();
 6         info.setAge(20);
 7         info.setScore(score);
 8 
 9         Person person = new Person();
10         person.setInfo(info);
11         person.setName("Tim");
12 
13         JSONObject obj = JSONObject.fromObject(person);
14         System.out.println(obj.toString());

输出:

 {
    "name": "Tim",
    "info": {
        "score": {
            "english": "A",
            "math": "B"
        },
        "age": 20
    }
}

 

4、把json数组转换成JsonObject数组:

 1         // 数组形式的json
 2         public static final String JSON_ARRAY = "[{‘name‘:‘tom‘},{‘name‘:‘john‘,‘age‘:20},{}]";
 3 
 4         JSONArray arr = JSONArray.fromObject(JSON_ARRAY);
 5         System.out.println(arr);
 6 
 7         for (int i = 0; i < arr.size(); i++) {
 8             JSONObject obj = arr.getJSONObject(i);
 9             System.out.println(obj.toString());
10         }

输出:

[{"name":"tom"},{"name":"john","age":20},{}]
{"name":"tom"}
{"name":"john","age":20}
{}

 

5、构造一个json字符串:

 1         JSONObject obj = new JSONObject();
 2         obj.put("name", "tom");
 3         obj.put("age", 19);
 4 
 5         // 子对象
 6         JSONObject objContact = new JSONObject();
 7         objContact.put("tel", "123456");
 8         objContact.put("email", "tom@test.com");
 9         obj.put("contact", objContact);
10 
11         // 子数组对象
12         JSONArray scoreArr = new JSONArray();
13         JSONObject objEnglish = new JSONObject();
14         objEnglish.put("course", "english");
15         objEnglish.put("result", 100);
16         objEnglish.put("level", "A");
17 
18         JSONObject objMath = new JSONObject();
19         objMath.put("course", "math");
20         objMath.put("result", 50);
21         objMath.put("level", "D");
22 
23         scoreArr.add(objEnglish);
24         scoreArr.add(objMath);
25 
26         obj.put("score", scoreArr);
27 
28         System.out.println(obj.toString());

输出:

{
    "score": [
        {
            "result": 100,
            "level": "A",
            "course": "english"
        },
        {
            "result": 50,
            "level": "D",
            "course": "math"
        }
    ],
    "contact": {
        "tel": "123456",
        "email": "tom@test.com"
    },
    "name": "tom",
    "age": 19
}

思考:输出的json中的字段的顺序有没有办法设置?

 

Java-json系列(二):用JSONObject解析和处理json数据