Java创建和解析Json数据方法(二)——org.json包的使用
(二)org.json包的使用
1.简介
3.构造json的示例用法
3.1 JSONObject.java
package orgjson;
/**
* 包含getter和setter的java bean类
* @author Zen9
*/
public class Student {
private String name;
private String sex;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package orgjson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.*;
public class JsonTest {
public static void constructorTest() {
String jsonStr = "{'name':'JTZen9','age':21}";
JSONObject strJson = new JSONObject(jsonStr); // 传入字符串
System.out.println("构造参数为String类:" + strJson);
Map<string object> map = new HashMap<string object>();
map.put("age", 21);
map.put("sex", "male");
map.put("name", "JTZen9");
JSONObject mapJson = new JSONObject(map); // 传入Map类型
System.out.println("构造参数为Map类:" + mapJson);
Student student = new Student();
student.setAge(21);
student.setName("JTZen9");
student.setSex("male");
JSONObject beanJson = new JSONObject(student); // 传入Bean类型
System.out.println("构造参数为Bean类:" + beanJson);
}
public static void putMethodTest() {
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("bookName", "JTZen9");
jsonObject1.put("age", 21);
System.out.println(jsonObject1);
JSONObject jsonObject2 = new JSONObject();
List<object> list = new ArrayList</object><object>();
for (int i = 1; i < 3; i++) {
Map<string object=""> map = new HashMap<string object="">();
map.put("title", "java程序设计 第" + i + "版");
map.put("price", i*20);
list.add(map);
}
jsonObject2.put("book", list);
System.out.println(jsonObject2);
Student student = new Student();
student.setAge(21);
student.setName("JTZen9");
student.setSex("male");
jsonObject2 = new JSONObject(student);
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("people", jsonObject2); //不可以直接传bean类对象put("people",student)
System.out.println(jsonObject3);
}
public static void main(String[] args) throws Exception {
constructorTest();
System.out.println("---------------------------------------------------------");
putMethodTest();
}
}
3.2 JSONArray.java
1.构造函数
官网上的JSONObject的构造函数如下:
package orgjson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.*;
public class JsonArrayTest {
public static void constructorTest() {
String jsonStr = "[{'name':'JTZen9','age':21}]";
JSONArray strJson = new JSONArray(jsonStr); // 传入字符串
System.out.println("构造参数为String类:" + strJson);
List<Object> list = new ArrayList<Object>();
for (int i = 1; i < 3; i++) {
Map<string object=""> map = new HashMap<string object="">();
map.put("title", "java程序设计 第" + i + "版");
map.put("price", i*20);
list.add(map);
}
JSONArray mapJson = new JSONArray(list); // 传入Collection类型
System.out.println("构造参数为Collection类:" + mapJson);
int[] numlist = new int[10];
for (int i = 0; i < numlist.length; i++) {
numlist[i] = i;
}
JSONArray arrayJson = new JSONArray(numlist); // 传入Array类型,实例1
System.out.println(arrayJson);
Student[] student = {new Student(),new Student()};
student[0].setAge(21);
student[0].setName("JTZen9");
student[0].setSex("male");
student[1].setAge(21);
student[1].setName("heiheihei");
student[1].setSex("female");
JSONArray beanJson = new JSONArray(student); // 传入Array类型,实例2
System.out.println("构造参数为Array类:" + beanJson);
}
public static void main(String[] args) {
constructorTest();
}
}
2.put方法创建
put方法中可以直接将int、double、Collection、Map等加进去,也可以添加下标来指定添加的位置:put(int index, java.util.Map value) ,使用put方法构造的JSON数组,如果传入的是数组,都会自动加一对中括号[ ],那么出来的结果就会有两层的中括号[ ],代码例子如下:
package orgjson;
import java.util.HashMap;
import java.util.Map;
import org.json.*;
public class JSONArrayTest {
public static void putMethodTest() {
JSONArray jsonArray1 = new JSONArray();
jsonArray1.put("JTZen9");
jsonArray1.put(21);
jsonArray1.put("male");
System.out.println(jsonArray1);
JSONArray jsonArray2 = new JSONArray();
Map<string object=""> map = new HashMap<string object="">();
map.put("title", "java程序设计 第2版");
map.put("price", 20);
jsonArray2.put(map); //传入一个map
System.out.println("传入一个Map:" + jsonArray2);
map.clear();
map.put("title", "java程序设计 第3版");
map.put("price", 30);
jsonArray2.put(map); //没有下标的直接在结果后面添加
System.out.println("没有指定下标:" + jsonArray2);
map.clear();
map.put("title", "java程序设计 第1版");
map.put("price", 10);
jsonArray2.put(0,map); //使用下标可以添加到自定义的位置
System.out.println("添加到第一个位置:" + jsonArray2);
Student[] student = { new Student(), new Student() };
student[0].setAge(21);
student[0].setName("JTZen9");
student[0].setSex("male");
student[1].setAge(21);
student[1].setName("heiheihei");
student[1].setSex("female");
JSONArray jsonArray3 = new JSONArray();
jsonArray3.put(student);
System.out.println("注意输出结果:" + jsonArray3);
}
public static void main(String[] args) {
putMethodTest();
}
}
3.3 JSONStringer.java & JSONWriter.java
②常用几个函数和说明:
package orgjson;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import org.json.*;
public class JSONWriterStringerTest {
public static void JSONStringerTest() throws Exception {
PrintWriter writer = new PrintWriter("test.txt");
JSONWriter jsonWriter = new JSONWriter(writer);
jsonWriter.object().key("name").value("JTZen9").key("age").value(21).key("sex").value("male").endObject();
writer.flush();
writer.close();
Map<string object=""> map1 = new HashMap<string object="">();
map1.put("age", 21);
map1.put("sex", "male");
map1.put("name", "jtzen9");
Map<string object=""> map2 = new HashMap<string object="">();
map2.put("age", 21);
map2.put("sex", "female");
map2.put("name", "heiheihei");
JSONStringer jsonStringer = new JSONStringer();
jsonStringer.array().value(map1).value(map2).endArray();
System.out.println(jsonStringer);
}
public static void main(String[] args) throws Exception {
JSONStringerTest();
}
}
3.4 JSONTokener.java
package orgjson;
import java.io.File;
import java.io.FileReader;
import org.json.*;
public class JSONTokenerTest {
public static void readJsonFile() throws Exception{
JSONTokener jsonTokener = new JSONTokener(new FileReader(new File("test.txt")));
JSONObject jsonObject = new JSONObject(jsonTokener);
System.out.println(jsonObject);
System.out.println("姓名:" + jsonObject.getString("name"));
System.out.println("年龄:" + jsonObject.getInt("age"));
}
public static void main(String[] args) throws Exception {
readJsonFile();
}
}
4.解析例子
[
{
"institute":{
"name":"Software Institute",
"grade":[
{
"name":"freshman",
"class":[
{
"no.":1,
"students":61
},
{
"no.":2,
"students":62
},
{
"no.":3,
"students":63
}
]
},
{
"name":"sophomore",
"class":[
{
"no.":1,
"students":51
},
{
"no.":2,
"students":52
},
{
"no.":3,
"students":53
}
]
},
{
"name":"junior",
"class":[
{
"no.":1,
"students":41
},
{
"no.":2,
"students":42
},
{
"no.":3,
"students":43
}
]
}
]
}
}
]
package orgjson;
import java.io.File;
import java.io.FileReader;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
public class JSONTest {
public static void main(String[] args) throws Exception {
JSONTokener jsonTokener = new JSONTokener(new FileReader(new File("json.txt")));
JSONArray jsonArray = new JSONArray(jsonTokener);//获取整个json文件的内容,因为最外层是数组,所以用JSONArray来构造
System.out.println(jsonArray);
//这个JSONArray数组只包含一个JSONObject对象,标为jsonObject1
JSONObject jsonObject1 = jsonArray.getJSONObject(0);
System.out.println(jsonObject1);
//jsonObject1只包含一个institute字段,这里获取这个字段内容赋给jsonObject2
JSONObject jsonObject2 = jsonObject1.getJSONObject("institute");
System.out.println(jsonObject2);
//jsonObject2包含name字段和grade字段,grade字段对应的是一个JSONArray数组
String valueOfname = jsonObject2.getString("name");
System.out.println(valueOfname);
JSONArray jsonArray2 = jsonObject2.getJSONArray("grade");
System.out.println(jsonArray2);
//jsonArray2数组包含3个对象,每个对象里面有name字段和class字段,这里获取第二个对象
JSONObject jsonObject3 = jsonArray2.getJSONObject(1);
System.out.println(jsonObject3);
//然后从jsonObject3对象里获取class字段对应的JSONArray数组
JSONArray jsonArray3 = jsonObject3.getJSONArray("class");
System.out.println(jsonArray3);
//下面直接获取no.等于3的students数量,过程都一样
int num = jsonArray3.getJSONObject(2).getInt("students");
System.out.println("最后获取的结果为:" + num);
}
}
5.结束语
之前解析json数据都是一直百度百度,别人怎么用就怎么用,做大作业时有时候会org.json包也导入,Gson包也导入,然后各用一点功能。现在想想其实只用一个org.json包就可以完全解决我的需求,只是之前一直没有总结各种用法,所以这两天看了下官网源码,总结了下学习笔记,还是收获蛮大的。
Java创建和解析Json数据方法(二)——org.json包的使用的更多相关文章
- Java创建和解析Json数据方法(四)——json-lib包的使用
(四)json-lib包的使用 既然json-lib包比org.json包重量级,那么json-lib包肯定有很多org.json包没有的类和方法,这篇笔记简单记录json-lib包中 ...
- Java创建和解析Json数据方法(五)——Google Gson包的使用
(五)Google Gson包的使用 1.简介 Gson包中,使用最多的是Gson类的toJson()和fromJson()方法: ①toJson():将java对象转化为json数据 ...
- Java学习-029-JSON 之三 -- 模仿 cssSelector 封装读取 JSON 数据方法
前文简单介绍了如何通过 json-20141113.jar 提供的功能获取 JSON 的数据,敬请参阅:Java学习-028-JSON 之二 -- 数据读取. 了解学习过 JQuery 的朋友都知道, ...
- Golang: 解析JSON数据之二
上次我们介绍了 Go 语言中序列化和反序列化 JSON 数据的两个方法 Marshal() 和 Unmarshal(),并以示例演示了它们的用法. 我们在例子中看到,需要事先声明好对应的结构体,才能跟 ...
- js进阶ajax读取json数据(ajax读取json和读取普通文本,和获取服务器返回数据(链接)都是一样的,在url处放上json文件的地址即可)
js进阶ajax读取json数据(ajax读取json和读取普通文本,和获取服务器返回数据(链接)都是一样的,在url处放上json文件的地址即可) 一.总结 ajax读取json和读取普通文本,和获 ...
- js中json数据简单处理(JSON.parse()和js中嵌套html)
js中json数据简单处理(JSON.parse()和js中嵌套html) 一.总结 1.html中嵌套js:<script>js代码</script> 2.js中嵌套html ...
- 将String类型的json数据转换为真正的json数据
问题 在做JavaWeb项目的时候,我们经常需要将Java对象转化为Json数据格式响应到前台页面,但是转化完成之后,看着是Json类型的数据格式,但实际上是字符串类型,在这里说两个方法将String ...
- Java创建和解析Json数据方法(三)——json-lib包的使用
(三)json-lib包的使用 这篇笔记主要介绍json-lib包的创建和解析json数据的方式,主要是的JSONObject.JSONArray和Java对象:beans, maps ...
- Java创建和解析Json数据方法——org.json包的使用(转)
org.json包的使用 1.简介 工具包org.json.jar,是一个轻量级的,JAVA下的json构造和解析工具包,它还包含JSON与XML, HTTP headers, Cookies, ...
随机推荐
- Stall Reservations POJ - 3190 (贪心+优先队列)
Stall Reservations Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 11002 Accepted: 38 ...
- bash的位置变量和特殊变量
bash编程的知识点:位置变量和特殊变量 位置参数变量: scirpt1.sh arg1 arg2 ... $0 $1 $2 ... ${10 ...
- luogu3469 [POI2008]BLO-Blockade
#include <iostream> #include <cstring> #include <cstdio> using namespace std; type ...
- luogu3808 luogu3796 AC自动机(简单版) AC自动机(加强版)
纪念一下我一晚上写了八遍AC自动机 这是加强版的: #include <iostream> #include <cstring> #include <cstdio> ...
- Selenium WebDriver-获取与切换浏览器窗口的句柄
通过selenium webdriver去切换浏览器的窗口,需要通过句柄,具体代码如下: #encoding=utf-8 import unittest import time import char ...
- 【转】C# 中的"yield"使用
C# 中的"yield"使用 yield是C#为了简化遍历操作实现的语法糖,我们知道如果要要某个类型支持遍历就必须要实现系统接口IEnumerable,这个接口后续实现比较繁琐要写 ...
- iOS开发,最新判断是否是手机号的正则表达式
最近项目里需要判断是否为手机号并发送验证码的功能,一下是实现方法.不过这个方法还是有些不足,只能判断输入的11位数的号段是否正确,无法判断手机号是否存在.不过勉强可以使用! + (NSString * ...
- Swift 3:新的访问控制fileprivate和open
在swift 3中新增加了两种访问控制权限 fileprivate和 open.下面将对这两种新增访问控制做详细介绍. fileprivate 在原有的swift中的 private其实并不是真正的私 ...
- 【Luogu】P3709大爷的字符串题(莫队算法)
题目链接 语文题啊…… 看题解发现是让求区间中最多的数的个数,于是果断理解了一会题解……莫队套上完事. sum[i]表示i这个数出现的次数,cnt[i]表示出现i次的数有几个,然后乱搞搞……就好了 # ...
- float浮动的学习
很早以前就接触过CSS,然后就在也没有深入了解过.今天突然遇到有人问了关系浮动的问题,碰巧没事就将内容整理下,与大家交流学习. 首先大家也应该都知道,div是块级元素,在页面中独占一行,自上而下排列, ...