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

(一)jar包下载

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

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

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

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

输出:

name is : tom
age is : 16

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

      // 嵌套的json字符串
public static final String JSON_MULTI = "{'name':'tom','score':{'Math':98,'English':90}}";
JSONObject obj = JSONObject.fromObject(JSON_MULTI);
System.out.println("name is : " + obj.get("name"));
System.out.println("score is : " + obj.get("score")); JSONObject scoreObj = (JSONObject) obj.get("score");
System.out.println("Math score is : " + scoreObj.get("Math"));
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类,否则会转换异常)

 public class Person {
private String name; private Info info; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Info getInfo() {
return info;
} public void setInfo(Info info) {
this.info = info;
} @Override
public String toString() {
return "Person [name=" + name + ", info=" + info + "]";
} }
 public class Info {
private int age;
private Score score; public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public Score getScore() {
return score;
} public void setScore(Score score) {
this.score = score;
} @Override
public String toString() {
return "Info [age=" + age + ", score=" + score + "]";
} }
 public class Score {
private String math;
private String english; public String getMath() {
return math;
} public void setMath(String math) {
this.math = math;
} public String getEnglish() {
return english;
} public void setEnglish(String english) {
this.english = english;
} @Override
public String toString() {
return "Score [math=" + math + ", english=" + english + "]";
} }

转换方法:

         Score score = new Score();
score.setEnglish("A");
score.setMath("B"); Info info = new Info();
info.setAge(20);
info.setScore(score); Person person = new Person();
person.setInfo(info);
person.setName("Tim"); JSONObject obj = JSONObject.fromObject(person);
System.out.println(obj.toString());

输出:

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

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

         // 数组形式的json
public static final String JSON_ARRAY = "[{'name':'tom'},{'name':'john','age':20},{}]"; JSONArray arr = JSONArray.fromObject(JSON_ARRAY);
System.out.println(arr); for (int i = 0; i < arr.size(); i++) {
JSONObject obj = arr.getJSONObject(i);
System.out.println(obj.toString());
}

输出:

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

5、构造一个json字符串:

         JSONObject obj = new JSONObject();
obj.put("name", "tom");
obj.put("age", 19); // 子对象
JSONObject objContact = new JSONObject();
objContact.put("tel", "123456");
objContact.put("email", "tom@test.com");
obj.put("contact", objContact); // 子数组对象
JSONArray scoreArr = new JSONArray();
JSONObject objEnglish = new JSONObject();
objEnglish.put("course", "english");
objEnglish.put("result", 100);
objEnglish.put("level", "A"); JSONObject objMath = new JSONObject();
objMath.put("course", "math");
objMath.put("result", 50);
objMath.put("level", "D"); scoreArr.add(objEnglish);
scoreArr.add(objMath); obj.put("score", scoreArr); 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中的字段的顺序有没有办法设置?

随机推荐

  1. atexit

    atexit - register a function to be called at normal process termination注册进程正常退出时的回调函数. #include < ...

  2. php对gzip文件或者字符串解压实例参考

    要采集一个网站,目标站采用了gzip压缩传输网页,本来应该只要发送一个http头 Accept-Encoding: identity或者干脆不发送这个头等,就可以使目标站返回没有经过gzip压缩的页面 ...

  3. 十年WEB技术发展历程

    一个小分享,知识有限,抛砖引玉. ajax 03年的时候我上六年级,那时候网吧刚在小县城的角落萌生.传奇,大话西游第一代网游一时风靡.我抱着试一试的心态给了网吧老板两块钱想申请个号玩玩,然后接下来的一 ...

  4. android 细节之 AndroidRuntimeException:This message is already in use

    今天在做项目处理消息队列的时候.遇到了这样一个问题.一个异常.AndroidRuntimeException:This message is already in use. 我当时的详细业务需求情境为 ...

  5. In the shell, what does “ 2>&1 ” mean?

    In a Unix shell, if I want to combine stderr and stdout into the stdout stream for further manipulat ...

  6. [转]unity3d所要知道的基础知识体系大纲,可以对照着学习,不定期更新 ... ... ... ...

    本文献给,想踏入3d游戏客户端开发的初学者. 毕业2年,去年开始9月开始转作手机游戏开发,从那时开始到现在一共面的游戏公司12家,其中知名的包括搜狐畅游.掌趣科技.蓝港在线.玩蟹科技.天神互动.乐元素 ...

  7. 发现保存GIF格式后相素发生变化咋办

    数学公式编辑器MathType主要的作用就是编辑公式用的,一些用户朋友编辑完公式希望把公式保存为“高分辨率”的GIF格式,但是在图片查看器中进行浏览查看时发现GIF的分辨率发生了变化,对于这种情况该如 ...

  8. day22模块和包

       一.模块 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类别: 1 使用python编写的代码(. ...

  9. water mark

    图片水印 https://www.oschina.net/p/watermarkjs?nocache=1542795300822 https://www.cnblogs.com/pengjunhao/ ...

  10. timus1716(概率dp)

    题意无比诡异. http://acm.timus.ru/problem.aspx?space=1&num=1716 俄罗斯的英文简直把我吓尿. 题意是对于输入:X1X2X3X4(Xi为YES或 ...