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

JSON:org.json的基本用法的更多相关文章

  1. Newtonsoft.Json(Json.net)的基本用法

    Newtonsoft.Json(Json.net)的基本用法 其它资料 JSON详解 添加引用: 使用NuGet,命令:install-package Newtonsoft.Json 实体类: pub ...

  2. 教程-delphi的开源json库:superobject,用法简介

    困惑一天的问题 一个语句搞定了... 回头细说. superobject中的{$DEFINE UNICODE} 就是它,这是json官方推荐的Delphi处理json的包,地址: http://www ...

  3. C++通过jsoncpp类库读写JSON文件-json用法详解

    介绍: JSON 是常用的数据的一种格式,各个语言或多或少都会用的JSON格式. JSON是一个轻量级的数据定义格式,比起XML易学易用,而扩展功能不比XML差多少,用之进行数据交换是一个很好的选择. ...

  4. Jquery的$.ajax、$.get、$.post发送、接收JSON数据及回调函数用法

    平时研究代码时,经常会遇到AJAX的相关用法,做项目时才真正体会到Ajax的强大之处(与服务器数据交互如此之便捷,更新DOM节点而不用刷新整个页面),以及运用的频繁程度.今天整理了一下自己之前没搞清楚 ...

  5. JSON.parse(),JSON.stringify(),jQuery.parseJSON()的用法

    1. JSON.parse(jsonString): 在一个字符串中解析出JSON对象 var str = '[{"href":"baidu.com",&quo ...

  6. 转:关于JSON.parse(),JSON.stringify(),jQuery.parseJSON()的用法

    1. JSON.parse(jsonString): 在一个字符串中解析出JSON对象 ? 1 2 3 var str = '[{"href":"baidu.com&qu ...

  7. Python数据结构同Json类型数据相互转换的用法

    在做Python接口自动化的时候,经常要用到Python数据结构同Json类型数据相互转换来供我们做进一步的验证提供数据,在此做个记录和总结 Python数据结构同Json类型数据相互转换的函数有:j ...

  8. json模块中函数的用法

    json模块中主要使用四个函数:json.load(),json.dump(),json.loads(),json.dumps() json.loads()是将一个json编码的字符串转换成pytho ...

  9. Python基础之模块:3、os模块 sys模块 json模块 json实战

    目录 一.os模块 1.创建目录 2.删除目录 3.查看指定路径下目录内容 4.删除/重命名文件 5.获取/切换当前目录 6.动态获取项目根路径 7.拼接/切割路径 8.判断文件.目录是否存在 9.判 ...

  10. .Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程

    JSON作为一种轻量级的数据交换格式,简单灵活,被很多系统用来数据交互,作为一名.NET开发人员,JSON.NET无疑是最好的序列化框架,支持XML和JSON序列化,高性能,免费开源,支持LINQ查询 ...

随机推荐

  1. SVN标准目录结构

    Trunk 这是SVN目录的主分支,表示日常开发中的项目,任何时候Trunk里包含的都是最新的开发代码. 这里的代码将会工作到你的下一个主要发布版本. Trunk应该只被用来开发将会成为你的下一个重要 ...

  2. nyoj 28 大数阶乘

    题目链接:nyoj 28 就是个简单的高精度,只是一开始我打表超内存了,然后用了各种技巧硬是把内存缩到了题目要求以下(5w+kb),感觉挺爽的,代码如下: #include<cstdio> ...

  3. 数据字典 dba_free_space及相对文件号RELATIVE_FNO 小结

    1.1 dba_free_space 1.1.1 概述 SQL> desc dba_free_space; Name Type Nullable Default Comments ------- ...

  4. mysql优化(三)–explain分析sql语句执行效率

    mysql优化(三)–explain分析sql语句执行效率 mushu 发布于 11个月前 (06-04) 分类:Mysql 阅读(651) 评论(0) Explain命令在解决数据库性能上是第一推荐 ...

  5. javascript AOP实现

    参考:http://www.cnblogs.com/rubylouvre/archive/2009/08/08/1541578.html function Person(){ this.say = f ...

  6. C++ Primer 第三章 标准库类型string运算

    1. 标准库类型 string string表示可变长的字符序列,使用string必须首先包含string头文件.如何初始化类的对象是由类本身决定的. int n; string s1;//默认初始化 ...

  7. 能源项目xml文件标签释义--<context:component-scan>

    <context:component-scan base-package="com.xindatai.ibs" use-default-filters="false ...

  8. Gradle 教程:第一部分,安装【翻译】

    原文地址:http://rominirani.com/2014/07/28/gradle-tutorial-part-1-installation-setup/ 在这篇教程里,我们将主要讲解如何在我们 ...

  9. media query ie8- 兼容实现总结

    虽然说响应式设计的理想状态是,需对pc/移动各种终端进行响应:但是现实是高分辨率的pc端与手机终端屏幕相差太大,像电商这样有大量图片和文字信息的同时排版要求精准的页面,设计一个同时适应高分辨率pc又适 ...

  10. 使用Visual Studio 2013进行单元测试--初级篇

    1.打开VS2013 --> 新建一个项目.这里我们默认创建一个控制台项目.取名为UnitTestDemo 2.在解决方案里面新增一个单元测试项目.取名为UnitTestDemoTest 创建完 ...