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
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的基本用法的更多相关文章
- 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查询 ...
随机推荐
- Oracle的参数文件
参数文件的作用: 它们是在数据库实例启动时候加载的,决定了数据库的物理结构.内存.数据库的限制及系统大量的默认值.数据库的各种物理属性.指定数据库控制文件名和路径等信息,是进行数据库设计和性能调优的重 ...
- CentOS 7 下的软件安装建议
https://seisman.info/how-to-install-softwares-under-centos-7.html https://seisman.info/linux-environ ...
- Android 可拖动列表项的ListView
需求分析 一个界面内两个ListView 我关注的栏目列表 上面的要长按后可拖动排序 点击减号后列表项消失 下面列表增加一行 同时存储相应字符串到本地作为标记 未关注栏目列表 普通ListView 点 ...
- iOS开发之 Xcode 5 下让你的应用在不同状态(debug, release)有不同的图标
http://nickcheng.com/post/unique-icons-for-your-app-in-different-state-in-xcode5-debug-release 应用在发布 ...
- UEditor 之查询当前编辑区域的状态是源码模式还是可视化模式
在使用百度的编辑器的时候,遇到了这样的一个问题: 解决方法是 使用了两个命令:
- css编码规范
css编码规范 https://segmentfault.com/a/1190000002460968 常用样式测试工具 W3C CSS validator:http://jigsaw.w3.org/ ...
- Java跟Javac,package与import
今天讨论一下2个指令与2个关键字. 这次的没有IDE环境,直接在txt文本里编程,在cmd里编译运行,搞清楚java的文件结构,还有怎么设置编译器查找类的路径.首先是javac,有一个可带参数java ...
- localhost访问不了
安装phpstudy后,localhost访问不了,在忙了很久之后,我吧virtualbox卸载了,把百度云也卸载了,然后就可以了,可能是因为公司的网络限制比较多,但百度云也太肯了, 也是看别人装了, ...
- git代码提交方式
https://my.oschina.net/tearlight/blog/193921 <a>github的提交方式 (1)git add .----------------- ...
- iOS设置app应用程序文件共享
1.iOSapp应用程序文件共享 当我们用itnues连接到设备时,在应用程序栏目下面,文件共享下,点击 对应的程序,即可以在程序右边栏目里面看到应用程序共享的数据, 此时,我们可以通过右下角的 添加 ...