JSONObject 的使用

来源:互联网 发布:wave动作数据mmd 编辑:程序博客网 时间:2024/06/08 02:27

JSONObject 的使用

项目中导入了 json-lib 包,但是在运行如下代码的时候还是出现了如下错误,究其原因是因为缺包,缺了如下5个包:

commons-beanutils-1.8.3

commons-lang-2.6 (注:导入最新的 3.1 版本会继续报如下错误)

commons-collections-3.2.1

commons-logging-1.1.1

ezmorph-1.0.6

Json Lib 下载:json-lib-2.4


import net.sf.json.JSONObject;

public class TestJson {
public static void main(String[] args){
Map<String, String> map = new HashMap<String, String>();
map.put("key", "value");
map.put("name", "abc");
JSONObject json = JSONObject.fromObject(map);
System.out.println(json);
}
}

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException

......

Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException


(一)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     @Override23     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     @Override22     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     @Override22     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
}


原创粉丝点击