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文本。

String myString = new JSONStringer().object()
.key("name")
.value("小猪")
.endObject()
.toString();

完整程序如下:

package com.ljh.jsondemo;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import org.junit.Test; public class JSONObjectTest { @Test
public void test() {
System.out.println(prepareJSONObject());
System.out.println(prepareJSONObject2());
} private static String prepareJSONObject(){
JSONObject studentJSONObject = new JSONObject();
try {
studentJSONObject.put("name", "Jason");
studentJSONObject.put("id", 20130001);
studentJSONObject.put("phone", "13579246810");
} catch (JSONException e) {
e.printStackTrace();
} return studentJSONObject.toString();
} private static String prepareJSONObject2(){
JSONStringer jsonStringer = new JSONStringer();
try {
jsonStringer.object();
jsonStringer.key("name");
jsonStringer.value("Jason");
jsonStringer.key("id");
jsonStringer.value(20130001);
jsonStringer.key("phone");
jsonStringer.value("13579246810");
jsonStringer.endObject();
} catch (JSONException e) {
e.printStackTrace();
}
return jsonStringer.toString();
} }

输出结果如下:

{"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:

 JSONObject object = ...
 String json = object.toString();

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类的相关方法。

package com.ljh.jsondemo;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.junit.Test; public class JSONTokenerTEst { @Test
public void test() {
System.out.println(getJSONContent());
} private static String JSONText = "{\"id\":20130001,\"phone\":\"13579246810\",\"name\":\"Jason\"}"; private static String getJSONContent(){
JSONTokener jsonTokener = new JSONTokener(JSONText);
JSONObject studentJSONObject;
String name = null;
int id = 0;
String phone = null;
try {
studentJSONObject = (JSONObject) jsonTokener.nextValue();
name = studentJSONObject.getString("name");
id = studentJSONObject.getInt("id");
phone = studentJSONObject.getString("phone"); } catch (JSONException e) {
e.printStackTrace();
}
return name + " " + id + " " + phone;
}
}

输出结果如下:

Jason  20130001   13579246810

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

private static String getJSONContent2(){
String name = null;
int id = 0;
String phone = null;
try {
JSONObject studentJSONObject = new JSONObject(JSONText);
name = studentJSONObject.getString("name");
id = studentJSONObject.getInt("id");
phone = studentJSONObject.getString("phone"); } catch (JSONException e) {
e.printStackTrace();
}
return name + " " + id + " " + phone;
}

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

版权声明:本文为博主原创文章,未经博主允许不得转载。

最新文章

  1. 组件RecyclerView的应用(一)
  2. Linux下开启关闭SeLinux
  3. python3-day4-python函数
  4. 【CF】438E. The Child and Binary Tree
  5. 升级到EF6 两个注意事项
  6. Convert between cv::Mat and QImage 两种图片类转换
  7. hdu3487 伸展树(区间搬移 区间旋转)
  8. 外企iOS开发的笔试题
  9. 万台规模下的SDN控制器集群部署实践
  10. 【0】python核心编程,第二章
  11. ASP.NET 4.0升级至ASP.NET 4.5需要注意的地方 【转】
  12. ASPxGridView-单元格合并
  13. Batch update returned unexpected row count from update [0] 异常处理
  14. 【快速入门ORM框架之Dapper】大牛勿进系列
  15. Python学习day9 函数Ⅰ(基础)
  16. Concept of function continuity in topology
  17. sql 日志文件截断收缩
  18. java 安装教程
  19. DEA和模糊综合评价
  20. python基础(3)-pycharm安装&for循环&format字符串&list列表&set集合使用

热门文章

  1. nginx学习十一 nginx启动流程
  2. 阿里云 django的一次web维护记录
  3. Exploring Micro-frameworks: Spring Boot--转载
  4. 给VG增加磁盘,给文件目录增加空间
  5. BZOJ2738: 矩阵乘法(整体二分)
  6. 一个理性战胜感性的成功案例:P2P投资和活期理财,纠结中提炼出来的1个数学问题
  7. RFID的工作流程
  8. css的三种表现形式
  9. pt模型
  10. Docker---(7)Docker安装启动RabbitMQ