JSONObject使用方法
转载:http://blog.csdn.net/dongzhouzhou/article/details/8664569
1.JSONObject介绍
JSONObject-lib包是一个beans,collections,maps,java arrays和xml和JSON互相转换的包。
2.下载jar包
http://files.cnblogs.com/java-pan/lib.rar
提供了除JSONObject的jar之外依赖的其他6个jar包,一共7个jar文件
说明:因为工作中项目用到的版本是1.1的对应jdk1.3的版本,故本篇博客是基于1.1版本介绍的。
对应此版本的javadoc下载路径如下:http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-1.1/
目前最新的版本为2.4,其他版本下载地址为http://sourceforge.net/projects/json-lib/files/json-lib/
3.项目环境:
system:WIN7 myeclipse:6.5 tomcat:5.0 JDK:开发环境和编译用的都是1.5
项目结构如下:
说明:本次用到的的文件只有工程目录json包下的JSONObject_1_3类和note.txt
4.class&method 基于1.1的API
做以下几点约定:
1.介绍基于JSONObject 1.1的API
2.只介绍常用的类和方法
3.不再介绍此版本中已经不再推荐使用
4.介绍的类和方法主要围绕本篇博客中用到的
JSONObject:A JSONObject is an unordered collection of name/value pairs.
是一个final类,继承了Object,实现了JSON接口
构造方法如下:
JSONObject();创建一个空的JSONObject对象
JSONObject(boolean isNull);创建一个是否为空的JSONObject对象
普通方法如下:
fromBean(Object bean);静态方法,通过一个pojo对象创建一个JSONObject对象
fromJSONObject(JSONObject object);静态方法,通过另外一个JSONObject对象构造一个JSONObject对象
fromJSONString(JSONString string);静态方法,通过一个JSONString创建一个JSONObject对象
toString();把JSONObject对象转换为json格式的字符串
iterator();返回一个
Iterator对象来遍历元素
接下来就是一些put/get方法,需要普通的get方法和pot方法做一下强调说明,API中是这样描述的:
A get
method returns a value if one can be found, and throws an exception if one cannot be found. An opt
method returns a default value instead of throwing an exception, and so is useful for obtaining optional values.
JSONArray:A JSONArray is an ordered sequence of values.
是一个final类,继承了Object,实现了JSON接口
构造方法如下:
JSONArray();构造一个空的JSONArray对象
普通方法如下:
fromArray(Object[] array);静态方法,通过一个java数组创建一个JSONArray对象
fromCollection(Collection collection);静态方法,通过collection集合对象创建一个JSONArray对象
fromString(String string);静态方法,通过一个json格式的字符串构造一个JSONArray对象
toString();把JSONArray对象转换为json格式的字符串
iterator();返回一个
Iterator对象来遍历元素
接下来同样是put/get方法……
XMLSerializer:Utility class for transforming JSON to XML an back.
一个继承自Object的类
构造方法如下:
XMLSerializer();创建一个
XMLSerializer对象
普通方法如下:
setRootName(String rootName);设置转换的xml的根元素名称
setTypeHintsEnabled(boolean typeHintsEnabled);设置每个元素是否显示type属性
write(JSON json);把json对象转换为xml,默认的字符编码是UTF-8,
需要设置编码可以用
write(JSON json, String encoding)
5.对XML和JSON字符串各列一个简单的例子
JSON:
{"password":"123456","username":"张三"}
xml
<?xml version="1.0" encoding="UTF-8"?>
<user_info>
<password>123456</password>
<username>张三</username>
</user_info>
start
新建web工程,工程名称JS,导入以下7个jar包,文件在前面的准备工作中下载路径。
说明:可以不用新建web工程,普通的java工程也可以完成本篇的的操作。至于为什么要导入处json包以外的其他6个包,我会把note.txt贴在最后,各位一看便知。
question1:后台接受到前台的json格式的字符串怎么处理?
![](https://common.cnblogs.com/images/copycode.gif)
1 public static void jsonToJAVA() {
2 System.out.println("json字符串转java代码");
3 String jsonStr = "{\"password\":\"123456\",\"username\":\"张三\"}";
4 JSONObject jsonObj = JSONObject.fromString(jsonStr);
5 String username = jsonObj.getString("username");
6 String password = jsonObj.optString("password");
7 System.out.println("json--->java\n username=" + username
8 + "\t password=" + password);
9 }
![](https://common.cnblogs.com/images/copycode.gif)
question2:后台是怎么拼装json格式的字符串?
![](https://common.cnblogs.com/images/copycode.gif)
1 public static void javaToJSON() {
2 System.out.println("java代码封装为json字符串");
3 JSONObject jsonObj = new JSONObject();
4 jsonObj.put("username", "张三");
5 jsonObj.put("password", "123456");
6 System.out.println("java--->json \n" + jsonObj.toString());
7 }
![](https://common.cnblogs.com/images/copycode.gif)
question3:json格式的字符串怎么转换为xml格式的字符串?
![](https://common.cnblogs.com/images/copycode.gif)
1 public static void jsonToXML() {
2 System.out.println("json字符串转xml字符串");
3 String jsonStr = "{\"password\":\"123456\",\"username\":\"张三\"}";
4 JSONObject json = JSONObject.fromString(jsonStr);
5 XMLSerializer xmlSerializer = new XMLSerializer();
6 xmlSerializer.setRootName("user_info");
7 xmlSerializer.setTypeHintsEnabled(false);
8 String xml = xmlSerializer.write(json);
9 System.out.println("json--->xml \n" + xml);
10 }
![](https://common.cnblogs.com/images/copycode.gif)
question4:xml格式的字符串怎么转换为json格式的字符串?
![](https://common.cnblogs.com/images/copycode.gif)
1 public static void xmlToJSON(){
2 System.out.println("xml字符串转json字符串");
3 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><user_info><password>123456</password><username>张三</username></user_info>";
4 JSON json=XMLSerializer.read(xml);
5 System.out.println("xml--->json \n"+json.toString());
6 }
![](https://common.cnblogs.com/images/copycode.gif)
question5:javabean怎么转换为json字符串?
![](https://common.cnblogs.com/images/copycode.gif)
1 public static void javaBeanToJSON() {
2 System.out.println("javabean转json字符串");
3 UserInfo userInfo = new UserInfo();
4 userInfo.setUsername("张三");
5 userInfo.setPassword("123456");
6 JSONObject json = JSONObject.fromBean(userInfo);
7 System.out.println("javabean--->json \n" + json.toString());
8 }
![](https://common.cnblogs.com/images/copycode.gif)
question6:javabean怎么转换为xml字符串?
![](https://common.cnblogs.com/images/copycode.gif)
1 public static void javaBeanToXML() {
2 System.out.println("javabean转xml字符串");
3 UserInfo userInfo = new UserInfo();
4 userInfo.setUsername("张三");
5 userInfo.setPassword("123456");
6 JSONObject json = JSONObject.fromBean(userInfo);
7 XMLSerializer xmlSerializer = new XMLSerializer();
8 String xml = xmlSerializer.write(json, "UTF-8");
9 System.out.println("javabean--->xml \n" + xml);
10 }
![](https://common.cnblogs.com/images/copycode.gif)
完整的JSONObject_1_3.java代码如下:
![](https://common.cnblogs.com/images/copycode.gif)
1 package json;
2
3 import net.sf.json.JSON;
4 import net.sf.json.JSONObject;
5 import net.sf.json.xml.XMLSerializer;
6
7 public class JSONObject_1_3 {
8 public static void javaToJSON() {
9 System.out.println("java代码封装为json字符串");
10 JSONObject jsonObj = new JSONObject();
11 jsonObj.put("username", "张三");
12 jsonObj.put("password", "123456");
13 System.out.println("java--->json \n" + jsonObj.toString());
14 }
15
16 public static void jsonToJAVA() {
17 System.out.println("json字符串转java代码");
18 String jsonStr = "{\"password\":\"123456\",\"username\":\"张三\"}";
19 JSONObject jsonObj = JSONObject.fromString(jsonStr);
20 String username = jsonObj.getString("username");
21 String password = jsonObj.optString("password");
22 System.out.println("json--->java\n username=" + username
23 + "\t password=" + password);
24 }
25
26 public static void jsonToXML() {
27 System.out.println("json字符串转xml字符串");
28 String jsonStr = "{\"password\":\"123456\",\"username\":\"张三\"}";
29 JSONObject json = JSONObject.fromString(jsonStr);
30 XMLSerializer xmlSerializer = new XMLSerializer();
31 xmlSerializer.setRootName("user_info");
32 xmlSerializer.setTypeHintsEnabled(false);
33 String xml = xmlSerializer.write(json);
34 System.out.println("json--->xml \n" + xml);
35 }
36
37 public static void javaBeanToJSON() {
38 System.out.println("javabean转json字符串");
39 UserInfo userInfo = new UserInfo();
40 userInfo.setUsername("张三");
41 userInfo.setPassword("123456");
42 JSONObject json = JSONObject.fromBean(userInfo);
43 System.out.println("javabean--->json \n" + json.toString());
44 }
45
46 public static void javaBeanToXML() {
47 System.out.println("javabean转xml字符串");
48 UserInfo userInfo = new UserInfo();
49 userInfo.setUsername("张三");
50 userInfo.setPassword("123456");
51 JSONObject json = JSONObject.fromBean(userInfo);
52 XMLSerializer xmlSerializer = new XMLSerializer();
53 String xml = xmlSerializer.write(json, "UTF-8");
54 System.out.println("javabean--->xml \n" + xml);
55 }
56
57 public static void xmlToJSON(){
58 System.out.println("xml字符串转json字符串");
59 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><user_info><password>123456</password><username>张三</username></user_info>";
60 JSON json=XMLSerializer.read(xml);
61 System.out.println("xml--->json \n"+json.toString());
62 }
63
64 public static void main(String args[]) {
65 // javaToJSON();
66 // jsonToJAVA();
67 // jsonToXML();
68 // javaBeanToJSON();
69 // javaBeanToXML();
70 xmlToJSON();
71 }
72 }
![](https://common.cnblogs.com/images/copycode.gif)
完整的UserInfo.java代码如下:
![](https://common.cnblogs.com/images/copycode.gif)
1 package json;
2
3 public class UserInfo {
4 public String username;
5 public String password;
6 public String getUsername() {
7 return username;
8 }
9 public void setUsername(String username) {
10 this.username = username;
11 }
12 public String getPassword() {
13 return password;
14 }
15 public void setPassword(String password) {
16 this.password = password;
17 }
18
19 }
![](https://common.cnblogs.com/images/copycode.gif)
result
代码和运行结果都已经贴在每个问题的后面,运行时直接用main方法分别对每个方法运行即可看到测试效果。
note.txt是报的对应的错误及解决方法,也从另一个方面说明为什么需要导入前面提到的jar包;
note.txt文件内容如下:
java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException
at java.lang.ClassLoader.defineClass0(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:537)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:251)
at java.net.URLClassLoader.access$100(URLClassLoader.java:55)
at java.net.URLClassLoader$1.run(URLClassLoader.java:194)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:187)
at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274)
at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302)
at generate.TestJSONObject.main(TestJSONObject.java:40)
Exception in thread "main"
解决方案:导入commons-lang-2.1.jar
java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at net.sf.json.JSONObject.<clinit>(JSONObject.java:125)
at generate.TestJSONObject.main(TestJSONObject.java:40)
Exception in thread "main"
解决方案:导入commons-logging.jar
java.lang.NoClassDefFoundError: org/apache/commons/beanutils/DynaBean
at net.sf.json.JSONObject.set(JSONObject.java:2164)
at net.sf.json.JSONObject.put(JSONObject.java:1853)
at net.sf.json.JSONObject.put(JSONObject.java:1806)
at generate.TestJSONObject.main(TestJSONObject.java:41)
Exception in thread "main"
解决方案:导入commons-beanutils.jar
java.lang.NoClassDefFoundError: net/sf/ezmorph/MorpherRegistry
at net.sf.json.util.JSONUtils.<clinit>(JSONUtils.java:65)
at net.sf.json.JSONObject.set(JSONObject.java:2164)
at net.sf.json.JSONObject.put(JSONObject.java:1853)
at net.sf.json.JSONObject.put(JSONObject.java:1806)
at generate.TestJSONObject.main(TestJSONObject.java:41)
Exception in thread "main"
解决方案:导入ezmorph-1.0.2.jar
java.lang.NoClassDefFoundError: org/apache/commons/collections/FastHashMap
at org.apache.commons.beanutils.PropertyUtils.<clinit>(PropertyUtils.java:208)
at net.sf.json.JSONObject.fromBean(JSONObject.java:190)
at net.sf.json.JSONObject.fromObject(JSONObject.java:437)
at net.sf.json.JSONObject.set(JSONObject.java:2196)
at net.sf.json.JSONObject.put(JSONObject.java:1853)
at net.sf.json.JSONObject.put(JSONObject.java:1806)
at generate.TestJSONObject.main(TestJSONObject.java:41)
Exception in thread "main"
解决方案:导入commons-collections-3.0.jar
Exception in thread "main" java.lang.NoClassDefFoundError: nu/xom/Serializer
at generate.TestJSONObject.jsonToXML(TestJSONObject.java:88)
at generate.TestJSONObject.main(TestJSONObject.java:96)
解决方案:导入xom-1.0d10.jar
几点说明:
1.注意UserInfo类的修饰符,用public修饰,变量username和password也用public修饰,最好单独的写一个类,这里就不贴出来了
2.以上json字符串和xml字符串都是最简单的形式,实际开发中json字符串和xml格式比这个复杂的多,
处理复杂的json字符串,可以封装写一个类继承HashMap,然后重写其put和get方法,以支持对类型为A[0].B及A.B的键值的读取和指定
3.以上6中情况在实际开发中可能有些不存在或不常用
存在的问题:
1.使用XMLSerializer的write方法生成的xml字符串的中文乱码问题
2.question4中的红色的log日志问题
2012-4-6 15:04:35 net.sf.json.xml.XMLSerializer getType
信息: Using default type string
原文链接:http://www.cnblogs.com/java-pan/archive/2012/04/07/JSONObject.html
JSONObject使用方法的更多相关文章
- json学习系列(2)-生成JSONObject的方法
生成JSONObject一般有两种方式,通过javabean或者map类型来生成.如下面的例子: 先定义一个User实体类: package com.pcitc.json; /** * 用户实体类 * ...
- (2)-生成JSONObject的方法
生成JSONObject一般有两种方式,通过javabean或者map类型来生成.如下面的例子: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 2 ...
- json教程系列(2)-生成JSONObject的方法
生成JSONObject一般有两种方式,通过javabean或者map类型来生成.如下面的例子: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 2 ...
- 大话 JSON 之 JSONObject.getString(“”) 方法 和 JSONObject.optString(“”) 的区别
运行以下代码: public static void main(String[] args) { JSONObject test = new JSONObject(); test.put(" ...
- 【转】 JSONObject使用方法
随笔- 46 文章- 0 评论- 132 JSONObject简介 本节摘要:之前对JSON做了一次简单的介 绍,并把JSON和XML做了一个简单的比较:那么,我就在想,如果是一个json格式的字 ...
- JSONObject使用方法详解
1.JSONObject介绍 JSONObject-lib包是一个beans,collections,maps,java arrays和xml和JSON互相转换的包. 2.下载jar包 http:// ...
- JsonArray和JsonObject遍历方法
一:遍历JsonArray String str = "[{name:'a',value:'aa'},{name:'b',value:'bb'},{name:'c',value:'cc'}, ...
- 使用net.sf.json包提供的JSONObject.toBean方法时,日期转化错误解决办法
解决办法: 需要在toBean之前添加配置 String[] dateFormats = new String[] {"yyyy-MM-dd HH:mm:ss"}; JSONUti ...
- org.codehaus.jettison.json.JSONObject使用方法
public static void main(String[] args) { System.out.println("测试开始"); File file = new File( ...
随机推荐
- Lingo (Spring Remoting) : Passing client credentials to the server
http://www.jroller.com/sjivan/entry/lingo_spring_remoting_passing_client Lingo (Spring Remoting) : P ...
- 语法之ADO.NET
ADO.NET的概念 由于本系列并不是主讲ADO.NET.所以这里笔者只会教上面定义有线连接方式相关的类.不管如何让我们先看一下ADO.NET类相关联的所有基类吧.这样子也方便我们下面的学习. 下面是 ...
- null!= xxx 和 xxx!=null有什么区别?
从意义上将没有区别,从编程规范上讲,第一种写法是为了防止写成:null = xxx
- dns解决测试微信二级域名访问问题
背景介绍: 1:解决本地不能通过域名访问问题: 2:解决微信设置二级域名且本地iis站点使用非80端口号问题: ps:网站中微信部分在global中设置了重定向,代码已经修改为必须通过“wechat. ...
- CodeForces 17E Palisection(回文树)
E. Palisection time limit per test 2 seconds memory limit per test 128 megabytes input standard inpu ...
- 接口测试工具 — jmeter(数据库操作)
1.导入jdbc jar包 2.配置MySQL连接 3.执行sql语句
- WebService 综合案例
1. 需求: 集成公网手机号归属地查询服务; 对外发布自己的手机号归属地查询服务; 提供查询界面 //1. 使用 wsimport 生成公网客户端代码 // 2. 创建 SEI 接口 @WebServ ...
- Linux命令之pip
使用pip进行install,sudo pip install xxx 使用pip进行update,sudo pip install --update xxx 使用pip设置超时时间,sudo pip ...
- Mac 启动和关闭rabbitmq
1.安装 brew install rabbitmq 2.启动及关闭RabbitMQ服务 前台启动 sudo ./rabbitmq-server 或 sudo su/usr/local/Cell ...
- dedecms中的内容页中的变量
{dede:php runphp='yes'} var_dump($refObj->Fields); {/dede:php}