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的基本使用方法的更多相关文章
- json入门(二)
背景 之前最早的时候,也见过类似于这样的字符串: {"list":[ {"ArticleId":7392749,"BlogId&q ...
- JSON入门指南--客户端处理JSON
在传统的Web开发过程中,前端工程师或者后台工程师会在页面上写后台的相关代码,比如在ASP.NET MVC4里面写如下代码: @Html.TextBoxFor(m => m.UserName, ...
- JSON入门之二:org.json的基本用法
java中用于解释json的主流工具有org.json.json-lib与gson,本文介绍org.json的应用. 官方文档: http://www.json.org/java/ http://de ...
- 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 ...
- Spring入门学习(二)三种实例化bean的方法
前面的哪一种就是通过构造函数来实例化对象 下面我们可能用到工厂方法来视力话对象,这样我们的配置文件又该怎么配置呢 <bean name="service2" class=&q ...
- JSON入门
一.简介 1.描述 1)JavaScript 对象表示法(JavaScript Object Notation) 2)存储和交换文本信息的语法.类似 XML 3)比 XML 更 ...
- C#的百度地图开发(二)转换JSON数据为相应的类
原文:C#的百度地图开发(二)转换JSON数据为相应的类 在<C#的百度地图开发(一)发起HTTP请求>一文中我们向百度提供的API的URL发起请求,并得到了返回的结果,结果是一串JSON ...
- python 模块二(os,json,pickle)
#################################总结##################### os常用 os.makedirs('baby/安哥拉/特斯拉/黄晓明') os.mkd ...
- 一、Ajax 二、JSON数据格式 三、Ajax+Jquery 四、分页的实现
一.Ajax概述###<1>概述 ###<2>组成 以XMLHttpRequest为核心,发送Ajax请求和接收处理结果 以javascript为语言基础 以XML/JSON作 ...
随机推荐
- RecyclerView 判断滑到底部 顶部 预加载 更多 分页 MD
Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...
- TJ Holowaychuk是怎样学习编程的?
TJ Holowaychuk是怎样学习编程的? 学习了:https://blog.csdn.net/wozaixiaoximen/article/details/49507111 Q:TJ Holow ...
- 直接修改class文件内容即使是文本会导致App异常,正确方式是修改java再用生成的class替换掉原有的class
前几天来了个小任务,把某项目中某人的邮件地址改了下. 由于对项目不熟悉,于是采用find方式找出app中所有包含某人邮件地址的文件都找出来了. xml,properties大约三四个,还有两个clas ...
- Session 共享(Custom模式)By Memcached(原创)
1.web.config配置: <machineKey decryptionKey="FD69B2EB9A11E3063518F1932E314E4AA1577BF0B824F369& ...
- MySQL Cluster配置文件-SQL节点4G内存
# Example MySQL config file for large systems. # # This is for a large system with memory = 512M whe ...
- JavaScript三(语法、关键保留字及变量)
基本概念 一.区分大小写 在ECMAScript中的一切(变量.函数名.操作符)都是区分大小写的. 如变量名test和Test分别表示两个不同的变量, 二.标识符 所谓标识符,就是指变量.函数.属性的 ...
- 算法笔记_108:第四届蓝桥杯软件类省赛真题(JAVA软件开发本科A组)试题解答
目录 1 世纪末的星期 2 振兴中华 3 梅森素数 4 颠倒的价牌 5 三部排序 6 逆波兰表达式 7 错误票据 8 带分数 9 剪格子 10 大臣的旅费 前言:以下试题解答代码部分仅供参考,若有不 ...
- PHP $_GET
$_GET 变量用于收集来自 method="get" 的表单中的值. $_GET 变量 $_GET 变量是一个数组,内容是由 HTTP GET 方法发送的变量名称和值. $_GE ...
- navicat 使用
sql是操作数据库中数据的语句,在不同的数据库中会略有不同,如mysql,postgreSQL,oracle,sqlserver,sqlite等等,但是sql的基础select.insert.upda ...
- python之函数用法staticmethod
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法staticmethod #http://www.cnblogs.com/hongfe ...