一、简介
org.json是常用的Json解析工具,主要提供JSONObject和JSONArray类,现在就各个类的使用解释如下。
二、准备
1.在使用org.json之前,我们应该先从该网址https://github.com/douglascrockford/JSON-java下载org.json源码,并将源码其加入到Eclipse中,即可调用。
2.查看相关的API文档,访问:https://github.com/douglascrockford/JSON-java。
https://github.com/stleary/JSON-Java-unit-test
三、讲解:
1.JSONObject:
-
是一个无序的键/值对集合。
-
它的表现形式是一个包裹在花括号的字符串,键和值之间使用冒号隔开,键值和键值之间使用逗号隔开。
-
内在形式是一个使用get()和opt()方法通过键来访问值,和使用put()方法通过键来添加或者替代值的对象。
-
值可以是任何这些类型:Boolean,JSONArray,JSONObject,Number和String,或者JOSONObject.NULL对象。
代码演示如下:
- public static void jsonObjectTest() {
- ᅠ ᅠ JSONObject jsonobj = new JSONObject("{'name':'xiazdong','age':20}");
- String name = jsonobj.getString("name");
- ᅠ ᅠ int age = jsonobj.getInt("age");
- System.out.println("name = " + name + ",age = " + age);
- }
注:JSONObject有很多optXXX方法,比如optBoolean, optString, optInt...
他们的意思是,如果这个jsonObject有这个属性,则返回这个属性,否则返回一个默认值。
2.JSONArray:
-
是一个有序的序列值。
-
它的表现形式是一个包裹在方括号的字符串,值和值之间使用逗号隔开。
-
内在形式是一个使用get()和opt()方法通过索引来访问值,和使用put()方法来添加或修改值的对象。
-
值可以是任何这些类型:Boolean,JSONArray,JSONObject,Number,和String,或者JSONObject.NULL对象。
代码演示如下:
- public static void jsonArrayTest() {
- ᅠ ᅠ JSONArray jsonarray = new JSONArray("[{'name':'xiazdong','age':20},{'name':'xzdong','age':15}]");
- ᅠ ᅠ for (int i = 0; i < jsonarray.length(); i++) {
- ᅠ ᅠ ᅠ ᅠᅠJSONObject jsonobj = jsonarray.getJSONObject(i);
- String name = jsonobj.getString("name");
- int age = jsonobj.getInt("age");
- System.out.println("name = " + name + ",age = " + age);
- }
- }
嵌套的JSONObject和JSONArray代码演示如下:
- public static void jsonObjectAndArrayTest() {
- ᅠ ᅠ String jsonstring = "{'name':'xiazdong','age':20,'book':['book1','book2']}";
- ᅠ ᅠ JSONObject jsonobj = new JSONObject(jsonstring);
- String name = jsonobj.getString("name");
- ᅠ ᅠ System.out.println("name" + ":" + name);
- int age = jsonobj.getInt("age");
- System.out.println("age" + ":" + age);
- ᅠ ᅠ JSONArray jsonarray = jsonobj.getJSONArray("book");
- ᅠ ᅠ for (int i = 0; i < jsonarray.length(); i++) {
- String book = jsonarray.getString(i);
- ᅠ ᅠ ᅠ ᅠ System.out.println("book" + i + ":" + book);
- }
- }
3.JSONStringer:
-
是一个用于快速构造JSON文本的工具
-
JSONWriter的子类
-
bject():开始一个对象,即添加{;enObject():结束一个对象,即添加}
-
array():开始一个数组,即添加[; endArray():结束一个数组,即添加]
-
key():表示添加一个key;value():表示添加一个value
代码演示如下:
- public static void jsonStringerTest() {
- ᅠ ᅠ JSONStringer stringer = new JSONStringer();
- stringer.object().key("name").value("xiazdong").key("age").value(20).endObject();
- ᅠ ᅠ System.out.println(stringer);
- }
负载的JSON格式写演示(PrintWriter+JSONStringer可以写入JSON文件):
- public static void jsonStringerTest2() throws FileNotFoundException {
- ᅠ ᅠ JSONStringer jsonStringer = new JSONStringer();
- ᅠ ᅠ JSONObject obj6 = new JSONObject();
- obj6.put("title", "book1").put("price", "$11");
- ᅠ ᅠ JSONObject obj3 = new JSONObject();
- obj3.put("book", obj6);
- ᅠ ᅠ obj3.put("author", new JSONObject().put("name", "author-1"));
- ᅠ ᅠ JSONObject obj5 = new JSONObject();
- obj5.put("title", "book2").put("price", "$22");
- ᅠ ᅠ JSONObject obj4 = new JSONObject();
- obj4.put("book", obj5);
- ᅠ ᅠobj4.put("author", new JSONObject().put("name", "author-2"));
- ᅠ ᅠ JSONArray obj2 = new JSONArray();
- obj2.put(obj3).put(obj4);
- ᅠ ᅠ JSONObject obj1 = new JSONObject();
- obj1.put("title", "BOOK");
- obj1.put("signing", obj2);
- jsonStringer.object().key("session").value(obj1).endObject();
- System.out.println(jsonStringer.toString());
- ᅠ ᅠ PrintWriter out = new PrintWriter(new FileOutputStream("1.txt"));
- ᅠ ᅠ out.println(jsonStringer.toString());
- out.close();
- }
4.JSONTokener
-
它和JSONObject和JSONArray的构造函数一起使用,用于解析JSON源字符串
代码演示如下(JSONObject+JSONTokener能够获取JSON格式文本对象):
- public static void JSONTokenerTest() throws FileNotFoundException {
- JSONObject jsonobj = new JSONObject(new JSONTokener(new FileReader(new File("1.txt"))));
- System.out.println(jsonobj.getJSONObject("session").getJSONArray("signing").getJSONObject(1).getJSONObject("book").getString("title"));
- }
注意:在Java中,JSON格式的字符串最好用单引号表示
JSON in Java [package org.json]JSON is a light-weight, language independent, data interchange format.See The files in this package implement JSON encoders/decoders in Java.It also includes the capability to convert between JSON and XML, HTTPheaders, Cookies, and CDL.This is a reference implementation. There is a large number of JSON packagesin Java. Perhaps someday the Java community will standardize on one. Untilthen, choose carefully.The license includes this restriction: "The software shall be used for good,not evil." If your conscience cannot live with that, then choose a differentpackage.The package compiles on Java 1.6-1.8.JSONObject.java: The JSONObject can parse text from a String or a JSONTokenerto produce a map-like object. The object provides methods for manipulating itscontents, and for producing a JSON compliant object serialization.JSONArray.java: The JSONObject can parse text from a String or a JSONTokenerto produce a vector-like object. The object provides methods for manipulatingits contents, and for producing a JSON compliant array serialization.JSONTokener.java: The JSONTokener breaks a text into a sequence of individualtokens. It can be constructed from a String, Reader, or InputStream.JSONException.java: The JSONException is the standard exception type thrownby this package.JSONPointer.java: Implementation of [JSON Pointer (RFC 6901)](). SupportsJSON Pointers both in the form of string representation and URI fragmentrepresentation.JSONString.java: The JSONString interface requires a toJSONString method,allowing an object to provide its own serialization.JSONStringer.java: The JSONStringer provides a convenient facility forbuilding JSON strings.JSONWriter.java: The JSONWriter provides a convenient facility for buildingJSON text through a writer.CDL.java: CDL provides support for converting between JSON and commadelimited lists.Cookie.java: Cookie provides support for converting between JSON and cookies.CookieList.java: CookieList provides support for converting between JSON andcookie lists.HTTP.java: HTTP provides support for converting between JSON and HTTP headers.HTTPTokener.java: HTTPTokener extends JSONTokener for parsing HTTP headers.XML.java: XML provides support for converting between JSON and XML.JSONML.java: JSONML provides support for converting between JSONML and XML.XMLTokener.java: XMLTokener extends JSONTokener for parsing XML text.Unit tests are maintained in a separate project. Contributing developers can test JSON-java pull requests with the code in this project:
package com.json;import java.text.ParseException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;/** * 使用json-lib构造和解析Json数据 * * @author Alexia * @date 2013/5/23 * */public class OrgJsonTest { /** * 构造Json数据 * * @return * @throws JSONException */ public static String BuildJson() throws JSONException { // JSON格式数据解析对象 JSONObject jo = new JSONObject(); // 下面构造两个map、一个list和一个Employee对象 Mapmap1 = new HashMap (); map1.put("name", "Alexia"); map1.put("sex", "female"); map1.put("age", "23"); Map map2 = new HashMap (); map2.put("name", "Edward"); map2.put("sex", "male"); map2.put("age", "24"); List
运行结果如下
五、与json-lib比较
json-lib和org.json的使用几乎是相同的,我总结出的区别有两点:
1. org.json比json-lib要轻量得多,前者没有依赖任何其他jar包,而后者要依赖ezmorph和commons的lang、logging、beanutils、collections等组件
2. json-lib在构造bean和解析bean时比org.json要方便的多,json-lib可直接与bean互相转换,而org.json不能直接与bean相互转换而需要map作为中转,若将bean转为json数据,首先需要先将bean转换为map再将map转为json,比较麻烦。
总之,还是那句话—适合自己的才是最好的,大家要按需选取使用哪种方法进行解析。最后给大家介绍两款解析Json数据的工具:一是在线工具JSON http://braincast.nl/samples/jsoneditor/);另一个是Eclipse的插件JSON Tree Analyzer,都很好用,推荐给大家使用!
http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/24/3096437.html