本文中主要介绍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. DataUml Design 教程3-模型与数据库同步

    上一节我们已经建立好了数据模型,那么怎么让数据模型和数据库进行同步呢?模型同步到数据库非常简单,只需要模型绑定到数据库即可.DataUml Design目前支持和Oracle与MS Server数据库 ...

  2. LeetCode406. Queue Reconstruction by Height Add to List

    Description Suppose you have a random list of people standing in a queue. Each person is described b ...

  3. nginx源代码分析--nginx模块解析

    nginx的模块很之多.能够觉得全部代码都是以模块的形式组织.这包含核心模块和功能模块,针对不同的应用场合.并不是全部的功能模块都要被用到,附录A给出的是默认configure(即简单的httpser ...

  4. Eclipse 创建 XML 文件

    Eclipse 创建 XML 文件 打开新建 XML 文件向导 你可以使用新建 XML 文件向导来创建 XML 文件.打开向导的方式有: 点击 File 菜单并选择 New > Other 点击 ...

  5. asp.net源程序编译为dll文件并调用的实现过程

    很多时候,我们需要将.cs文件单独编译成.dll文件,这就需要使用csc命令将.cs文件编译成.dll动态链接库文件.具体的操作步骤如下: 打开命令窗口->输入cmd到控制台->cd C: ...

  6. 4、easyUI-七种布局(layout)

    1.为网页创建边框布局 边框布局(border layout)提供五个区域:east.west.north.south.center.以下是一些通常用法: north 区域可以用来显示网站的标语. s ...

  7. MVC架构模式概述

    MVC MVC概述: Model–view–controller (MVC) is a software architectural pattern for implementing user int ...

  8. 【BZOJ1937】[Shoi2004]Mst 最小生成树 KM算法(线性规划)

    [BZOJ1937][Shoi2004]Mst 最小生成树 Description Input 第一行为N.M,其中 表示顶点的数目, 表示边的数目.顶点的编号为1.2.3.…….N-1.N.接下来的 ...

  9. JAVA性能调试+JProfiler使用相关

    一.JProfiler下载.安装与激活 1.1 下载 直接官网下载(https://www.ej-technologies.com/download/jprofiler/files) 建议下载9.X系 ...

  10. IOS开发复习笔记(1)-OC基础知识

    在上班之余学习IOS已经有三个多月了,因为基础有些薄弱从OC的基本语法开始学习的,相继看了青柚子和红柚子的书,现在在看编程实战,趁这个机会好好的总结一下: 1.命名约定 对象类型和名称一致,以免混淆 ...