JSON:org.json的基本用法
java中用于解释json的主流工具有org.json、json-lib与gson,本文介绍org.json的应用。
官方文档:
http://developer.android.com/reference/org/json/package-summary.html
1、主要类
Classes
|
A dense indexed sequence of values. |
|
|
A modifiable set of name/value mappings. |
|
|
Implements |
|
|
Parses a JSON (RFC 4627) encoded string into the corresponding object. |
Exceptions
|
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 toendArray()and every call toobject()must have a matching call toendObject(). - Arrays may not contain keys (property names).
- Objects must alternate keys (property names) and values.
- Values are inserted with either literal
valuecalls, 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的基本用法的更多相关文章
- Newtonsoft.Json(Json.net)的基本用法
Newtonsoft.Json(Json.net)的基本用法 其它资料 JSON详解 添加引用: 使用NuGet,命令:install-package Newtonsoft.Json 实体类: pub ...
- 教程-delphi的开源json库:superobject,用法简介
困惑一天的问题 一个语句搞定了... 回头细说. superobject中的{$DEFINE UNICODE} 就是它,这是json官方推荐的Delphi处理json的包,地址: http://www ...
- C++通过jsoncpp类库读写JSON文件-json用法详解
介绍: JSON 是常用的数据的一种格式,各个语言或多或少都会用的JSON格式. JSON是一个轻量级的数据定义格式,比起XML易学易用,而扩展功能不比XML差多少,用之进行数据交换是一个很好的选择. ...
- Jquery的$.ajax、$.get、$.post发送、接收JSON数据及回调函数用法
平时研究代码时,经常会遇到AJAX的相关用法,做项目时才真正体会到Ajax的强大之处(与服务器数据交互如此之便捷,更新DOM节点而不用刷新整个页面),以及运用的频繁程度.今天整理了一下自己之前没搞清楚 ...
- JSON.parse(),JSON.stringify(),jQuery.parseJSON()的用法
1. JSON.parse(jsonString): 在一个字符串中解析出JSON对象 var str = '[{"href":"baidu.com",&quo ...
- 转:关于JSON.parse(),JSON.stringify(),jQuery.parseJSON()的用法
1. JSON.parse(jsonString): 在一个字符串中解析出JSON对象 ? 1 2 3 var str = '[{"href":"baidu.com&qu ...
- Python数据结构同Json类型数据相互转换的用法
在做Python接口自动化的时候,经常要用到Python数据结构同Json类型数据相互转换来供我们做进一步的验证提供数据,在此做个记录和总结 Python数据结构同Json类型数据相互转换的函数有:j ...
- json模块中函数的用法
json模块中主要使用四个函数:json.load(),json.dump(),json.loads(),json.dumps() json.loads()是将一个json编码的字符串转换成pytho ...
- Python基础之模块:3、os模块 sys模块 json模块 json实战
目录 一.os模块 1.创建目录 2.删除目录 3.查看指定路径下目录内容 4.删除/重命名文件 5.获取/切换当前目录 6.动态获取项目根路径 7.拼接/切割路径 8.判断文件.目录是否存在 9.判 ...
- .Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程
JSON作为一种轻量级的数据交换格式,简单灵活,被很多系统用来数据交互,作为一名.NET开发人员,JSON.NET无疑是最好的序列化框架,支持XML和JSON序列化,高性能,免费开源,支持LINQ查询 ...
随机推荐
- Python中的__new__()方法的使用
__new__() 函数只能用于从object继承的新式类. 先看下object类中对__new__()方法的定义: class object: @staticmethod # known cas ...
- 【服务器环境搭建-Centos】系统分区 待续
df命令查看,显示/dev/vda,而不是sda或hda ,为什么? 虚拟机为了提升性能,一般使用virtio作为磁盘驱动,在虚拟机里面磁盘会显示成vda而不是传统的sda,有什么办法可以让他显示成s ...
- PKCS #1 RSA Encryption Version 1.5
PKCS #1 RSA Encryption Version 1.5 在进行RSA运算时需要将源数据D转化为Encryption block(EB).其中pkcs1padding V1.5的填充模式 ...
- 记录---base64
什么是Base64呢? Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,大家可以查看RFC2045-RFC2049,上面有MIME的详细规范.Base64编码可用于在HTTP环境下 ...
- mac中openfire启动失败的解决方式
不知为何,几次出现这个问题了 解决方法:使用终端命令 1:sudo chmod -R 777 /usr/local/openfire/bin 2:cd /usr/local/openfire/bin ...
- 使用fragmenttabhost后,子fragment怎么获取ID?怎么用getSharedPreferences
使用fragmenttabhost后,子fragment怎么获取ID?怎么用getSharedPreferences public View onCreateView(LayoutInflater i ...
- 图片左右滚动的js代码
html代码 <div class="demo" id="demo" style="overflow:hidden; width:660px; ...
- Unity 3D中的内存管理
本文欢迎转载,但烦请保留此行出处信息:http://www.onevcat.com/2012/11/memory-in-unity3d/ Unity3D在内存占用上一直被人诟病,特别是对于面向移动设备 ...
- jQuery笔记一
陆续更新中..... 1,创建标签的时候可以提前写好,以后用clone()方法克隆即可. 如: var div=$("<div></div>"); var ...
- Windows 8 IIS配置PHP运行环境
在Windows 8 的IIS(8.0)中搭建PHP运行环境: 一:安装IIS服务器 1.进入控制面板>>程序和功能>>打开或关闭Windows 功能,找到Internet信息 ...