Java:JSON解析工具-org.json

java

一、简介 

org.json是Java常用的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对象。 

代码演示如下: 

 

[java] view plain copy

 

 

  1. public static void jsonObjectTest() {   
  2. ᅠ ᅠ JSONObject jsonobj = new JSONObject("{\'name\':\'xiazdong\',\'age\':20}");   
  3.     String name = jsonobj.getString("name");   
  4. ᅠ ᅠ int age = jsonobj.getInt("age");   
  5.     System.out.println("name = " + name + ",age = " + age);   
  6. }   

 

注:JSONObject有很多optXXX方法,比如optBoolean, optString, optInt... 

他们的意思是,如果这个jsonObject有这个属性,则返回这个属性,否则返回一个默认值。 

2.JSONArray: 

  • 是一个有序的序列值。 

  • 它的表现形式是一个包裹在方括号的字符串,值和值之间使用逗号隔开。 

  • 内在形式是一个使用get()和opt()方法通过索引来访问值,和使用put()方法来添加或修改值的对象。 

  • 值可以是任何这些类型:Boolean,JSONArray,JSONObject,Number,和String,或者JSONObject.NULL对象。 

代码演示如下: 

 

[plain] view plain copy

 

 

  1. public static void jsonArrayTest() {   
  2. ᅠ ᅠ JSONArray jsonarray = new JSONArray("[{\'name\':\'xiazdong\',\'age\':20},{\'name\':\'xzdong\',\'age\':15}]");   
  3. ᅠ ᅠ for (int i = 0; i < jsonarray.length(); i++) {   
  4. ᅠ ᅠ ᅠ ᅠᅠJSONObject jsonobj = jsonarray.getJSONObject(i);   
  5.         String name = jsonobj.getString("name");   
  6.         int age = jsonobj.getInt("age");   
  7.         System.out.println("name = " + name + ",age = " + age);   
  8.     }   
  9. }  

 

嵌套的JSONObject和JSONArray代码演示如下: 

 

[plain] view plain copy

 

 

  1. public static void jsonObjectAndArrayTest() {   
  2. ᅠ ᅠ String jsonstring = "{\'name\':\'xiazdong\',\'age\':20,\'book\':[\'book1\',\'book2\']}";   
  3. ᅠ ᅠ JSONObject jsonobj = new JSONObject(jsonstring);   
  4.    
  5.     String name = jsonobj.getString("name");   
  6. ᅠ ᅠ System.out.println("name" + ":" + name);   
  7.    
  8.     int age = jsonobj.getInt("age");   
  9.     System.out.println("age" + ":" + age);   
  10.    
  11. ᅠ ᅠ JSONArray jsonarray = jsonobj.getJSONArray("book");   
  12. ᅠ ᅠ for (int i = 0; i < jsonarray.length(); i++) {   
  13.         String book = jsonarray.getString(i);   
  14. ᅠ ᅠ ᅠ ᅠ System.out.println("book" + i + ":" + book);   
  15.     }    
  16. }   

 

3.JSONStringer: 

  • 是一个用于快速构造JSON文本的工具 

  • JSONWriter的子类 

  • bject():开始一个对象,即添加{;enObject():结束一个对象,即添加} 

  •  array():开始一个数组,即添加[; endArray():结束一个数组,即添加] 

  • key():表示添加一个key;value():表示添加一个value 

代码演示如下: 

 

[java] view plain copy

 

 

  1. public static void jsonStringerTest() {   
  2. ᅠ ᅠ JSONStringer stringer = new JSONStringer();   
  3.     stringer.object().key("name").value("xiazdong").key("age").value(20).endObject();   
  4. ᅠ ᅠ System.out.println(stringer);   
  5. }  

 

负载的JSON格式写演示(PrintWriter+JSONStringer可以写入JSON文件): 

 

[plain] view plain copy

 

 

  1. public static void jsonStringerTest2() throws FileNotFoundException {   
  2. ᅠ ᅠ JSONStringer jsonStringer = new JSONStringer();   
  3. ᅠ ᅠ JSONObject obj6 = new JSONObject();   
  4.     obj6.put("title", "book1").put("price", "$11");   
  5. ᅠ ᅠ JSONObject obj3 = new JSONObject();   
  6.     obj3.put("book", obj6);   
  7. ᅠ ᅠ obj3.put("author", new JSONObject().put("name", "author-1"));   
  8.    
  9. ᅠ ᅠ JSONObject obj5 = new JSONObject();   
  10.     obj5.put("title", "book2").put("price", "$22");   
  11. ᅠ ᅠ JSONObject obj4 = new JSONObject();   
  12.     obj4.put("book", obj5);   
  13.  ᅠ ᅠobj4.put("author", new JSONObject().put("name", "author-2"));   
  14.    
  15. ᅠ ᅠ JSONArray obj2 = new JSONArray();   
  16.     obj2.put(obj3).put(obj4);   
  17.    
  18. ᅠ ᅠ JSONObject obj1 = new JSONObject();   
  19.     obj1.put("title", "BOOK");   
  20.     obj1.put("signing", obj2);   
  21.    
  22.     jsonStringer.object().key("session").value(obj1).endObject();   
  23.     System.out.println(jsonStringer.toString());   
  24.    
  25. ᅠ ᅠ PrintWriter out = new PrintWriter(new FileOutputStream("1.txt"));   
  26. ᅠ ᅠ out.println(jsonStringer.toString());   
  27.     out.close();   
  28. }   

 

4.JSONTokener 

  • 它和JSONObject和JSONArray的构造函数一起使用,用于解析JSON源字符串 

代码演示如下(JSONObject+JSONTokener能够获取JSON格式文本对象): 

 

[java] view plain copy

 

 

  1. public static void JSONTokenerTest() throws FileNotFoundException {   
  2.     JSONObject jsonobj = new JSONObject(new JSONTokener(new FileReader(new File("1.txt"))));   
  3.     System.out.println(jsonobj.getJSONObject("session").getJSONArray("signing").getJSONObject(1).getJSONObject("book").getString("title"));   
  4. }  

注意:在Java中,JSON格式的字符串最好用单引号表示 

 

JSON in Java [package org.json]

JSON is a light-weight, language independent, data interchange format.

See http://www.JSON.org/

The files in this package implement JSON encoders/decoders in Java.

It also includes the capability to convert between JSON and XML, HTTP

headers, Cookies, and CDL.

This is a reference implementation. There is a large number of JSON packages

in Java. Perhaps someday the Java community will standardize on one. Until

then, 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 different

package.

The package compiles on Java 1.6-1.8.

JSONObject.java: The JSONObject can parse text from a String or a JSONTokener

to produce a map-like object. The object provides methods for manipulating its

contents, and for producing a JSON compliant object serialization.

JSONArray.java: The JSONObject can parse text from a String or a JSONTokener

to produce a vector-like object. The object provides methods for manipulating

its contents, and for producing a JSON compliant array serialization.

JSONTokener.java: The JSONTokener breaks a text into a sequence of individual

tokens. It can be constructed from a String, Reader, or InputStream.

JSONException.java: The JSONException is the standard exception type thrown

by this package.

JSONPointer.java: Implementation of

[JSON Pointer (RFC 6901)](https://tools.ietf.org/html/rfc6901). Supports

JSON Pointers both in the form of string representation and URI fragment

representation.

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 for

building JSON strings.

JSONWriter.java: The JSONWriter provides a convenient facility for building

JSON text through a writer.

CDL.java: CDL provides support for converting between JSON and comma

delimited lists.

Cookie.java: Cookie provides support for converting between JSON and cookies.

CookieList.java: CookieList provides support for converting between JSON and

cookie 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:

https://github.com/stleary/JSON-Java-unit-test

 

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对象

Map<String, String> map1 = new HashMap<String, String>();

map1.put("name", "Alexia");

map1.put("sex", "female");

map1.put("age", "23");

Map<String, String> map2 = new HashMap<String, String>();

map2.put("name", "Edward");

map2.put("sex", "male");

map2.put("age", "24");

List<Map> list = new ArrayList<Map>();

list.add(map1);

list.add(map2);

Employee employee = new Employee();

employee.setName("wjl");

employee.setSex("female");

employee.setAge(24);

// 将Map转换为JSONArray数据

JSONArray ja = new JSONArray();

ja.put(map1);

System.out.println("JSONArray对象数据格式:");

System.out.println(ja.toString());

// 将Javabean转换为Json数据(需要Map中转)

JSONObject jo1 = JsonHelper.toJSON(employee);

System.out.println("\n仅含Employee对象的Json数据格式:");

System.out.println(jo1.toString());

// 构造Json数据,包括一个map和一个含Employee对象的Json数据

jo.put("map", ja);

jo.put("employee", jo1.toString());

System.out.println("\n最终构造的JSON数据格式:");

System.out.println(jo.toString());

return jo.toString();

}

/**

* 解析Json数据

*

* @param jsonString

* Json数据字符串

* @throws JSONException

* @throws ParseException

*/

public static void ParseJson(String jsonString) throws JSONException,

ParseException {

JSONObject jo = new JSONObject(jsonString);

JSONArray ja = jo.getJSONArray("map");

System.out.println("\n将Json数据解析为Map:");

System.out.println("name: " + ja.getJSONObject(0).getString("name")

+ " sex: " + ja.getJSONObject(0).getString("sex") + " age: "

+ ja.getJSONObject(0).getInt("age"));

String jsonStr = jo.getString("employee");

Employee emp = new Employee();

JsonHelper.toJavaBean(emp, jsonStr);

System.out.println("\n将Json数据解析为Employee对象:");

System.out.println("name: " + emp.getName() + " sex: " + emp.getSex()

+ " age: " + emp.getAge());

}

/**

* @param args

* @throws JSONException

* @throws ParseException

*/

public static void main(String[] args) throws JSONException, ParseException {

// TODO Auto-generated method stub

ParseJson(BuildJson());

}

}

 

 

运行结果如下

五、与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 Edit(http://braincast.nl/samples/jsoneditor/);另一个是Eclipse的插件JSON Tree Analyzer,都很好用,推荐给大家使用!

http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/24/3096437.html

 

以上是 Java:JSON解析工具-org.json 的全部内容, 来源链接: utcz.com/z/392937.html

回到顶部