JSON入门之二:org.json的基本用法

java中用于解释json的主流工具有org.json、json-lib与gson,本文介绍org.json的应用。

官方文档:

http://www.json.org/java/

http://developer.android.com/reference/org/json/package-summary.html

 

1、主要类

Classes


JSONArray

A dense indexed sequence of values. 

JSONObject

A modifiable set of name/value mappings. 

JSONStringer

Implements toString() and toString()

JSONTokener

Parses a JSON (RFC 4627) encoded string into the corresponding object. 

Exceptions


JSONException

Thrown to indicate a problem with the JSON API. 

 

2、构建一个JSON文本的方法

(1)使用JSONObject的构造方法,然后toString。

创建一个JSONObject对象后,再使用put(String, Object)方法添加键值对。

toString()方法将JSONObject对象按照JSON的标准格式进行封装。

(2)使用JSONStringer创建JSON文本。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. String myString = new JSONStringer().object()     
  2. .key("name")    
  3. .value("小猪")     
  4. .endObject()    
  5. .toString();  
完整程序如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.ljh.jsondemo;  
  2.   
  3. import org.json.JSONException;  
  4. import org.json.JSONObject;  
  5. import org.json.JSONStringer;  
  6. import org.junit.Test;  
  7.   
  8. public class JSONObjectTest {  
  9.   
  10.     @Test  
  11.     public void test() {  
  12.         System.out.println(prepareJSONObject());  
  13.         System.out.println(prepareJSONObject2());  
  14.     }  
  15.       
  16.     private static String prepareJSONObject(){  
  17.         JSONObject studentJSONObject = new JSONObject();  
  18.         try {  
  19.             studentJSONObject.put("name""Jason");  
  20.             studentJSONObject.put("id"20130001);  
  21.             studentJSONObject.put("phone""13579246810");  
  22.         } catch (JSONException e) {  
  23.             e.printStackTrace();  
  24.         }  
  25.           
  26.         return studentJSONObject.toString();  
  27.     }  
  28.       
  29.     private static String prepareJSONObject2(){  
  30.         JSONStringer jsonStringer = new JSONStringer();  
  31.         try {  
  32.             jsonStringer.object();  
  33.             jsonStringer.key("name");  
  34.             jsonStringer.value("Jason");  
  35.             jsonStringer.key("id");  
  36.             jsonStringer.value(20130001);  
  37.             jsonStringer.key("phone");  
  38.             jsonStringer.value("13579246810");  
  39.             jsonStringer.endObject();  
  40.         } catch (JSONException e) {  
  41.             e.printStackTrace();  
  42.         }  
  43.         return jsonStringer.toString();  
  44.     }  
  45.   
  46. }  
输出结果如下:

{"id":20130001,"phone":"13579246810","name":"Jason"}
{"name":"Jason","id":20130001,"phone":"13579246810"}

结论:

(1)使用JSONObject构造的JSON文本顺序杂乱,使用JSONStringer则按顺序排列。

(2)关于二者之间的比较,android官方文档认为:

 Most application developers should use those methods directly and disregard this API. For example:

<span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="typ" style="color: rgb(102, 0, 102);">JSONObject</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="kwd" style="color: rgb(0, 0, 136);">object</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="pun" style="color: rgb(102, 102, 0);">=</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="pun" style="color: rgb(102, 102, 0);">...</span><span class="pln" style="color: rgb(0, 0, 0);">
 </span><span class="typ" style="color: rgb(102, 0, 102);">String</span><span class="pln" style="color: rgb(0, 0, 0);"> json </span><span class="pun" style="color: rgb(102, 102, 0);">=</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="kwd" style="color: rgb(0, 0, 136);">object</span><span class="pun" style="color: rgb(102, 102, 0);">.</span><span class="pln" style="color: rgb(0, 0, 0);">toString</span><span class="pun" style="color: rgb(102, 102, 0);">();</span>

Stringers only encode well-formed JSON strings. In particular:

  • The stringer must have exactly one top-level array or object.
  • Lexical scopes must be balanced: every call to array() must have a matching call to endArray() and every call to object() must have a matching call to endObject().
  • Arrays may not contain keys (property names).
  • Objects must alternate keys (property names) and values.
  • Values are inserted with either literal value calls, or by nesting arrays or objects.
Calls that would result in a malformed JSON string will fail with a  JSONException .

This class provides no facility for pretty-printing (ie. indenting) output. To encode indented output, use toString(int) or toString(int).

Some implementations of the API support at most 20 levels of nesting. Attempts to create more than 20 levels of nesting may fail with a JSONException.

Each stringer may be used to encode a single top level value. Instances of this class are not thread safe. Although this class is nonfinal, it was not designed for inheritance and should not be subclassed. In particular, self-use by overrideable methods is not specified. See Effective Java Item 17, "Design and Document or inheritance or else prohibit it" for further information.

即:

一般情况下使用JSONObject即可,但对于一些嵌套的JSON,某些JSONArray没有key,只有value等特殊情况,则使用JSONStringer.


3、读取JSON文本内容。

使用JSONTokener类的相关方法。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.ljh.jsondemo;  
  2.   
  3. import org.json.JSONException;  
  4. import org.json.JSONObject;  
  5. import org.json.JSONTokener;  
  6. import org.junit.Test;  
  7.   
  8. public class JSONTokenerTEst {  
  9.   
  10.     @Test  
  11.     public void test() {  
  12.         System.out.println(getJSONContent());  
  13.     }  
  14.       
  15.     private static String JSONText = "{\"id\":20130001,\"phone\":\"13579246810\",\"name\":\"Jason\"}";  
  16.       
  17.     private static String getJSONContent(){  
  18.         JSONTokener jsonTokener = new JSONTokener(JSONText);   
  19.         JSONObject studentJSONObject;  
  20.         String name = null;  
  21.         int id = 0;  
  22.         String phone = null;  
  23.         try {  
  24.             studentJSONObject = (JSONObject) jsonTokener.nextValue();  
  25.             name = studentJSONObject.getString("name");  
  26.             id = studentJSONObject.getInt("id");  
  27.             phone = studentJSONObject.getString("phone");  
  28.               
  29.         } catch (JSONException e) {  
  30.             e.printStackTrace();  
  31.         }  
  32.         return name + "  " + id + "   " + phone;  
  33.     }  
  34. }  
输出结果如下:

Jason  20130001   13579246810

事实上,使用JSONObject的构造方法也可直接创建JSONObject对象。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. private static String getJSONContent2(){  
  2.     String name = null;  
  3.     int id = 0;  
  4.     String phone = null;  
  5.     try {  
  6.         JSONObject studentJSONObject = new JSONObject(JSONText);   
  7.         name = studentJSONObject.getString("name");  
  8.         id = studentJSONObject.getInt("id");  
  9.         phone = studentJSONObject.getString("phone");  
  10.           
  11.     } catch (JSONException e) {  
  12.         e.printStackTrace();  
  13.     }  
  14.     return name + "  " + id + "   " + phone;  
  15. }  

总结:单纯使用JSONObject可以解决大部分的JSON处理问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值