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的基本用法 分类: C_OHTERS 2014-05-14 11:25 6001人阅读 评论(0) 收藏的更多相关文章

  1. sqoop 1.4.4-cdh5.1.2快速入门 分类: C_OHTERS 2015-06-06 11:40 208人阅读 评论(0) 收藏

    一.快速入门 (一)下载安装 1.下载并解压 wget http://archive.cloudera.com/cdh5/cdh/5/sqoop-1.4.4-cdh5.1.2.tar.gz tar - ...

  2. 【solr专题之二】配置文件:solr.xml solrConfig.xml schema.xml 分类: H4_SOLR/LUCENCE 2014-07-23 21:30 1959人阅读 评论(0) 收藏

    1.关于默认搜索域 If you are using the Lucene query parser, queries that don't specify a field name will use ...

  3. 【solr基础教程之二】索引 分类: H4_SOLR/LUCENCE 2014-07-18 21:06 3331人阅读 评论(0) 收藏

    一.向Solr提交索引的方式 1.使用post.jar进行索引 (1)创建文档xml文件 <add> <doc> <field name="id"&g ...

  4. HIVE快速入门 分类: B4_HIVE 2015-06-06 11:27 59人阅读 评论(0) 收藏

    (一)简单入门 1.创建一个表 create table if not exists ljh_emp( name string, salary float, gender string) commen ...

  5. Gora官方文档之二:Gora对Map-Reduce的支持 分类: C_OHTERS 2015-01-31 11:27 232人阅读 评论(0) 收藏

    参考官方文档:http://gora.apache.org/current/tutorial.html 项目代码见:https://code.csdn.net/jediael_lu/mygoradem ...

  6. 博弈论入门小结 分类: ACM TYPE 2014-08-31 10:15 73人阅读 评论(0) 收藏

    文章原地址:http://blog.csdn.net/zhangxiang0125/article/details/6174639 博弈论:是二人或多人在平等的对局中各自利用对方的策略变换自己的对抗策 ...

  7. Makefile 入门与基本语法 分类: C/C++ ubuntu 2015-05-18 11:16 466人阅读 评论(0) 收藏

    在我看来,学会写简单的Makefile,阅读较复杂的makefile,是每一个Linux程序员都必须拥有的基本素质.Makefile可以自动识别哪些源文件被更改过,需要重新编译,那些不需要.从而节省大 ...

  8. 【Lucene4.8教程之二】索引 2014-06-16 11:30 3845人阅读 评论(0) 收藏

    一.基础内容 0.官方文档说明 (1)org.apache.lucene.index provides two primary classes: IndexWriter, which creates ...

  9. C#中的线程(上)-入门 分类: C# 线程 2015-03-09 10:56 53人阅读 评论(0) 收藏

    1.     概述与概念 C#支持通过多线程并行地执行代码,一个线程有它独立的执行路径,能够与其它的线程同时地运行.一个C#程序开始于一个单线程,这个单线程是被CLR和操作系统(也称为"主线 ...

随机推荐

  1. 爬虫爬数据时,post数据乱码解决的方法

    近期在写一个爬虫,目标站点是:http://zx.bjmemc.com.cn/.可能是为了防止被爬取数据,它给自身数据加了密. 用谷歌自带的抓包工具也不能捕获到数据. 于是下了Fiddler.     ...

  2. windows7下安装Office2010提示需要安装MSXML6.10.1129

    平台:Windows 7 问题:刚刚下载的ghost Win 7,安装过程一切顺利,进入系统后把集成的软件全部卸载,清理完垃圾,安装了VC库,在安装Office2010时提示需要安装MSXML6.10 ...

  3. php学习笔记3

    1.PHP 定界符 EOF 的作用就是按照原样,包括换行格式什么的,输出在其内部的东西: 2.在 PHP 定界符 EOF 中的任何特殊字符都不需要转义: 3.PHP 定界符 EOF

  4. vector转数组

    vector转数组 由于vector内部的数据是存放在连续的存储空间,vector转数组事实上只需要获取vector中第一个数据的地址和数据的长度即可.如果仅仅是传参,无需任何操作,直接传地址即可,如 ...

  5. Spring学习总结(11)——Spring JMS MessageConverter介绍

    消息转换器MessageConverter MessageConverter的作用主要有两方面,一方面它可以把我们的非标准化Message对象转换成我们的目标Message对象,这主要是用在发送消息的 ...

  6. Objective-C - 类的静态常量

    创建头文件(.h), 导出常量: // Constants.h FOUNDATION_EXPORT NSString *const MyFirstConstant; FOUNDATION_EXPORT ...

  7. matlab 文件路径问题

    1. fullfile:路径补全 f = fullfile(filepart1,...,filepartN) 显然可变参数之间填充的路径分隔符(path separator),会根据操作系统而变化: ...

  8. python3对序列求绝对值

    http://www.cnblogs.com/itdyb/p/5731804.html     一开始我是这样写的,据说这样写python2是可以的: myList = [-1,2,-3,4,-5,6 ...

  9. (错误记录)Vue: Unknown custom element

    错误: vue.js:634 [Vue warn]: Unknown custom element: <ve-pie> - did you register the component c ...

  10. ThinkPHP5.0---删除数据

    删除特定记录 public function delete() { // 获取要删除的对象:关键字为16 $Teacher = Teacher::); // 删除对象 $Teacher->del ...