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. json入门(二)

    背景 之前最早的时候,也见过类似于这样的字符串: {"list":[           {"ArticleId":7392749,"BlogId&q ...

  2. JSON入门指南--客户端处理JSON

    在传统的Web开发过程中,前端工程师或者后台工程师会在页面上写后台的相关代码,比如在ASP.NET MVC4里面写如下代码: @Html.TextBoxFor(m => m.UserName, ...

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

    java中用于解释json的主流工具有org.json.json-lib与gson,本文介绍org.json的应用. 官方文档: http://www.json.org/java/ http://de ...

  4. JSON入门之二:org.json的基本用法 分类: C_OHTERS 2014-05-14 11:25 6001人阅读 评论(0) 收藏

    java中用于解释json的主流工具有org.json.json-lib与gson,本文介绍org.json的应用. 官方文档: http://www.json.org/java/ http://de ...

  5. Spring入门学习(二)三种实例化bean的方法

    前面的哪一种就是通过构造函数来实例化对象 下面我们可能用到工厂方法来视力话对象,这样我们的配置文件又该怎么配置呢 <bean name="service2" class=&q ...

  6. JSON入门

    一.简介     1.描述         1)JavaScript 对象表示法(JavaScript Object Notation) 2)存储和交换文本信息的语法.类似 XML 3)比 XML 更 ...

  7. C#的百度地图开发(二)转换JSON数据为相应的类

    原文:C#的百度地图开发(二)转换JSON数据为相应的类 在<C#的百度地图开发(一)发起HTTP请求>一文中我们向百度提供的API的URL发起请求,并得到了返回的结果,结果是一串JSON ...

  8. python 模块二(os,json,pickle)

    #################################总结##################### os常用 os.makedirs('baby/安哥拉/特斯拉/黄晓明') os.mkd ...

  9. 一、Ajax 二、JSON数据格式 三、Ajax+Jquery 四、分页的实现

    一.Ajax概述###<1>概述 ###<2>组成 以XMLHttpRequest为核心,发送Ajax请求和接收处理结果 以javascript为语言基础 以XML/JSON作 ...

随机推荐

  1. 关于PHP写的投票网站之刷票风云

    最近学校导航站找我让我给他们做一个投票系统的网站,我一口答应了,他们只是要求不准刷票情况出现,我也一口答应了..我答应的太干脆了. 然后我便开始做这个网站,网站做出来没花太多时间,并且我是用IP来判断 ...

  2. apache 伪静态 .htaccess

    虽然网上有很多教程,但是我在这里进行简单对我用到的总结一下. 加载Rewrite模块: 在conf目录下httpd.conf中找到 LoadModule rewrite_module modules/ ...

  3. 自适应图片宽度的jQuery焦点幻灯轮播代码

    自适应图片宽度的jQuery焦点幻灯轮播代码 注意要1.7.2版本的jq才支持点击后显示点击的图片,不然就是一直顺序播放 演示   XML/HTML Code <div id="sli ...

  4. FrameWork逆向工程之MotioPI

    在BI项目建设的过程中我们一般都是有备份的,而且这个是必须有的!特别是例如ETL Model,还有Data Model这一类的元数据,这些东西如果我们没有备份,而恰好的我们的开发模型又在某一天离我们而 ...

  5. Compiling LIBFFM On OSX 10.9

    原文:http://blog.josephmisiti.com/compiling-libffm-on-osx-10.9/ I recently tried to compile LIBFFM (Fi ...

  6. Java 实例 - 队列(Queue)用法

    队列是一种特殊的线性表,它只允许在表的前端进行删除操作,而在表的后端进行插入操作. LinkedList类实现了Queue接口,因此我们可以把LinkedList当成Queue来用. 以下实例演示了队 ...

  7. 反汇编基本原理与x86指令构造

    反汇编基本原理与x86指令构造 概要:旨在讲述程序的二进制代码转换到汇编.即反汇编的基本原理.以及 x86 架构的 CPU 的指令构造,有这个基础后就能够自己编写汇编程序了,也能够将二进制代码数据转换 ...

  8. C#.NET常见问题(FAQ)-listView如何显示网格线

    把GridLines设置为True     更多教学视频和资料下载,欢迎关注以下信息: 我的优酷空间: http://i.youku.com/acetaohai123   我的在线论坛: http:/ ...

  9. Power Network (poj 1459 网络流)

    Language: Default Power Network Time Limit: 2000MS   Memory Limit: 32768K Total Submissions: 23407   ...

  10. fcntl的区域锁定

    文件中的某个部分被锁定了,但其他的程序可以访问这个文件的其他部分,称为文件段锁定或文件区域锁定.经常使用文件区域锁定是fcntl函数. #include <sys/types.h> #in ...