本文中主要介绍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. LeetCode543. Diameter of Binary Tree

    Description Given a binary tree, you need to compute the length of the diameter of the tree. The dia ...

  2. NDK 安装小结

    建议先看后面的错误,可以先执行那些命令以免出现相关问题. chmod a+x android-ndk-r10c-linux-x86_64.bin ./android-ndk-r10c-linux-x8 ...

  3. easyui常见属性

    4)onBeforeClose:当面板关闭前激活.                 5)onClose:当面板关闭后激活.                 6)onBeforeDestroy:当面板销 ...

  4. 解决pip安装模块报错Cannot fetch index base URL http://pypi.python.org/simple/

    产生这个问题的原因呢和github一样,因为他们用的cdn被墙.经小伙伴反馈,解决办法如下. 通过指定国内镜像源来安装: pip --trusted-host 镜像源 install 模块名 -i 镜 ...

  5. Python - except不指定异常类别(转)

    From:How to properly ignore Exceptions? try: doSomething() except: pass or try: doSomething() except ...

  6. 很easy的js双向绑定框架(二):控制器继承

    初衷 上一篇已经实现了数据的双向绑定,但model的控制范围是整个文档.在实际project中必需要有作用范围,以便做ui模块的拆分. 这一篇,我们希望实现像angularjs一样的控制器继承: 1. ...

  7. -webkit-transition: all .2s ease-in-out;

    W3C标准中对CSS3的transition这是样描述的:CSS的transition允许CSS的属性值在一定的时间区间内平滑地过渡.这种效果可以在鼠标单击.获得焦点.被点击或对元素任何改变中触发,并 ...

  8. android 微信朋友分享,朋友圈分享

    android 微信朋友分享,朋友圈分享 包名必须写成  com.weixin WXEntryActivity package com.weixin.wxapi; import android.app ...

  9. C#安装,启动,停止,卸载Windows服务

    public class OptionServices    {        //安装服务        public static void InstallService(string filep ...

  10. Python2.6升级Python2.7

    Python2.6升级2.7 由于Centos6系列自带的python版本为2.6.6,然而有很多应用需要依赖于python2.7来实现,所以有了这个升级的需求.升级原理很简单,无非就是下载.编译.安 ...