本文中主要介绍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. ASP.NET MVC 表单提交多层子级实体集合数据到控制器中

    于遇到了项目中实体类嵌套多层子级实体集合,并且子级实体集合的数据需要提交保存到数据库中的问题.针对此情况需要进行一些特殊的处理才可以将整个 实体类及子级实体集合数据提交表单到控制器中,解决的方法是根据 ...

  2. 从C#到Swift,Swift学习笔记

    最近在学习IOS,我一直使用的是C#来开发,对Java .C.C++也有一定的了解.最近入手了一台Air,想试着学习IOS开发. 如果你不是C#和Java阵营的,如果你对Swift没有兴趣,就不用往下 ...

  3. Spring读取配置文件的方式总结

    一.基于XML配置的方式 1.使用 PropertyPlaceholderConfigurer - 在 applicationContext.xml 中配置: <context:property ...

  4. python中SQL的使用

    # 常用的关系型数据库有 mysql postgresql sqlite 等(具体区别上课再说) # # 传统数据库以表的形式存储数据 # 一张表可以有很多个字段 # 以用户表为例, 存储 4 个数据 ...

  5. Linux Linux程序练习二

    /* 编写一个程序读取a.txt文件,将文件内容数字从小到大排序,并将排序结果写入b.txt. */ #include <stdio.h> #include <stdlib.h> ...

  6. 寒城攻略:Listo 教你用Swift 语言编写 IOS 平台流媒体播放器

    先展示播放器效果:   依然继承 Listo 本人的强迫症,还是从最初到完毕完整的写一个攻略来记录一下,这里声明 Listo 本人也是看了非常多的戴维营攻略才总结分享给大家这一篇攻略的. 首先,Lis ...

  7. html 模版

    使用后台开发语言的都很了解语言的动态性给开发带来的好处,PHP,aspx,jsp页面都可以直接使用相应的语法和变量,输出的事就交给解释器或编译器了,用起来方便快捷,但需要额外的解释工作: 例如php模 ...

  8. python_selenium之xpath的使用

    python_selenium之xpath的使用 一.xpath介绍 Xpath:XPath即为XML路径语言,它是一种用来确定XML(标准通用标记语言的子集)文档中某部分位置的语言.XPath基于X ...

  9. CGI FastCGI PHP-CGI PHP-FRM

    CGI(Common GateWay Interface )通用网关接口,CGI可以让一个客户端,从网页浏览器向执行在Web服务器上的程序请求数据.CGI描述了客户端和这个程序之间传输数据的一种协议标 ...

  10. Android开发:《Gradle Recipes for Android》阅读笔记(翻译)3.3——整合resource文件

    问题: 想要在product的flavor里面改变图片,文字或者其它资源. 解决方案: 在flavor里面增加合适的资源目录,并且改变他们包含的值. 讨论: 考虑下3.2章的“hello world ...