$Java-json系列(二):用JSONObject解析和处理json数据
本文中主要介绍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中的字段的顺序有没有办法设置?
随机推荐
- Java并发编程(三)概念介绍
在构建稳健的并发程序时,必须正确使用线程和锁.但是这终归只是一些机制.要编写线程安全的代码,其核心在于要对状态访问操作进行管理,特别是对共享的(Shared)和可变的(Mutable)状态的访问. 对 ...
- imx6中iomux IO复用
IOMUX Controller (IOMUXC) IO多路复用控制器1.overviewThe IOMUX Controller (IOMUXC), together with the IOMUX, ...
- samba实现文件共享
很多时候,做嵌入式开发,都是在windows上安装虚拟,在虚拟机中安装Linux操作系统.这个时候,我们经常需要Linux操作系统下有一个目录能在windows下自由访问.要想实现这个功能我们只需要在 ...
- 阿里云服务器 端口开放问题 浏览器钟输入ip 访问服务器
在这里先用一堆粗口强烈吐槽阿里云服务器控制台,屎一样的界面,简直非人类的操作.想找一个功能简直无从下手. 场景: 今天刚在阿里云买了个服务器,打算愉快的用五分钟将数据库,apache,安装完毕,然后去 ...
- ThinkPHP与EasyUI整合之三(searchbox):在datagrid中查询指定记录
在datagrid中toolbar添加searchbox查询框,根据列范围查询数据,先看效果图: 1. searchbox采用easyui的Demo例子,再加以js扩展,根据datagrid中的列数据 ...
- JNDI架构提供了一组标准的独立于命名系统的API
JNDI架构提供了一组标准的独立于命名系统的API,这些API构建在与命名系统有关的驱动之上.这一层有助于将应用与实际数据源分离,因此不管应用访问的是LDAP.RMI.DNS.还是其他的目录服务.换句 ...
- setTimeout里无法调用鼠标事件的event
问题的由来是下面这段代码: middleOnmouseLeave: function (event) { setTimeout(function () { event.currentTarget.st ...
- 百度-设置-搜索设置-每页显示50条-保存设置-打印alert信息-accept确定
一.场景: 代码: #coding:utf-8from selenium import webdriverfrom selenium.webdriver.common.action_chains im ...
- python:编写登陆接口(day 1)
作业要求: 输入用户名,密码 认证成功显示欢迎信息 输入错误三次后锁定用户 Readme 1.user_id.txt是存放用户id及密码的文件 2.user_lock.txt是存放被锁定的用户id的文 ...
- java8 关于日期的处理
Java8 为我们提供了一种新的日期格式:LocalDate和LocalDateTime 获取当前的时间及前一天时间的方法: import java.time.LocalDateTime; impor ...