json基本用法(1)

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处理问题。

全部评论

相关推荐

04-16 10:27
已编辑
美团_Saas_后端开发
今天周一休息,突发奇想写一篇阶段总结。如题,我已经去了一个和Java彻底毫无关联的行业。曾经我以为自己能在计算机行业发光发热,拿到美团offer那会感觉自己天都亮了。没想到刚入行一年多就当了逃兵。从最开始的热爱到现在一看到代码就厌恶,不知道自己经历了什么。所以我去干什么了?答案是:在成都当了租房销售。上班那会压力大了就念叨着去干租房中介,但是一直下不去这个决心,想着自己学了四年多的计算机知识,终究还是不甘心。终于在某一天准备八股文的时候,看着无数篇和工作内容关系不大的理论知识,那一刻下定决心,决定尝试一下销售行业,也算是给自己一个交代。后面阴差阳错的投了成都自如去当租房管家,没想到面试很顺利,在当天一百多个面试的人里面,我成为了为数不多通过的几个幸运儿之一。目前已经培训通过,正式入职,也开了单,有压力但是每天过得很开心,真心喜欢那种和人交流的感觉,哪怕是最后没有选择找我租房。说这些也是想告诉那些大三,大四正在找Java实习而焦虑的同学:你们现在还年轻,选择很多,容错率也很高,可以尽情去尝试自己喜欢的行业和工作。不用因为某一次的面试没通过或者简历石沉大海而焦虑,更不用因为身边人都在挤编程的独木桥就强迫自己跟风。也算是自己的碎碎念吧,也希望自己能在新的领域取得一点小成就。也祝牛油工作顺利!
沉淀小子:干啥都不丢人啊,生存是必须要的,销售很考验一个人综合素质能力的,好的销售人脉和资源可不比写字楼的白领差啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务