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, ...
随机推荐
- 并查集:POJ1182-食物链(并查集比较高端的应用)
食物链 Time Limit: 1000MS Memory Limit: 10000K Description 动物王国中有三类动物A,B,C,这三类动物的食物链构成了有趣的环形.A吃B, B吃C,C ...
- STM8 EEPROM心得
对于STM8来说,其内部的EEPROM确实是个不错的东西,而且STM8S103/105价格已经非常便宜了,当然也可以用STM8S003/005代替,而且价格更便宜,大概在,1.2/2.0元左右,比10 ...
- luogu3690 【模板】Link Cut Tree (动态树)
参考there和there 题单 #include <iostream> #include <cstdio> using namespace std; int n, m, va ...
- 如何用treap写luogu P3391
treap大法好!!! splay什么的都是异端 --XZZ 先%FHQ为敬 (fhq)treap也是可以搞区间翻转的 每次把它成(1~L-1)(L~R)(R+1~n)三块然后打标记拼回去 对于有标记 ...
- alidoing --使用JS实现多语言框架、喜欢的请进、、瓦特平台!
大家好! 多语言实现的案例:http://alidoing.com/或者http://www.alidoing.com/ 图:切换语言界面 JS代码实现: 1.首先新建一个对象langobj,当然对象 ...
- Flash中国地图 开放源码
Flash中国地图,以Object为数据源,便于实现基于中国地图的可视化项目. 特征: swc,便于导入到Flex项目中 数据源为Object,比XML更方便 数据驱动的地图块颜色和Hover颜色 可 ...
- Leetcode27--->Remove Element(移除数组中给定元素)
题目:给定一个数组array和一个值value,移除掉数组中所有与value值相等的元素,返回新的数组的长度:要求:不能分配额外的数组空间,且必须使用原地排序的思想,空间复杂度O(1); 举例: Gi ...
- Linux安装Scala
下载Scala地址http://downloads.typesafe.com/scala/2.10.6/scala-2.10.6.tgz然后解压Scala到指定目录 tar -zxvf scala-2 ...
- 【SDOJ 3741】 【poj2528】 Mayor's posters
Description The citizens of Bytetown, AB, could not stand that the candidates in the mayoral electio ...
- ip 核生成 rom 及questasim仿真时需要注意的问题
IP 核生成 ROM 步骤1:Tools --> MegaWizard Plug-In Manager 步骤2:Create a new custom megafuction variation ...