JSONObject使用方法详解json解析

JSONObject-lib包是一个beans,collections,maps,java arrays和xml和JSON互相转换的包,本文给大家介绍jsonobject使用方法相关知识,感兴趣的朋友一起学习吧

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.介绍的类和方法主要围绕本篇博客中用到的

?
1
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:

?
1
{ "password" : "123456" , "username" : "张三" }

xml

?
1
2
3
4
5
<?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格式的字符串怎么处理?

?
1
2
3
4
5
6
7
8
9
public static void jsonToJAVA() {
System.out.println( "json字符串转java代码" );
String jsonStr = "{\"password\":\"\",\"username\":\"张三\"}" ;
JSONObject jsonObj = JSONObject.fromString(jsonStr);
String username = jsonObj.getString( "username" );
String password = jsonObj.optString( "password" );
System.out.println( "json--->java\n username=" + username
+ "\t password=" + password);
}

question2:后台是怎么拼装json格式的字符串?

?
1
2
3
4
5
6
7
public static void javaToJSON() {
System.out.println( "java代码封装为json字符串" );
JSONObject jsonObj = new JSONObject();
jsonObj.put( "username" , "张三" );
jsonObj.put( "password" , "" );
System.out.println( "java--->json \n" + jsonObj.toString());
}

 

question3:json格式的字符串怎么转换为xml格式的字符串?

?
1
2
3
4
5
6
7
8
9
10
public static void jsonToXML() {
System.out.println( "json字符串转xml字符串" );
String jsonStr = "{\"password\":\"\",\"username\":\"张三\"}" ;
JSONObject json = JSONObject.fromString(jsonStr);
XMLSerializer xmlSerializer = new XMLSerializer();
xmlSerializer.setRootName( "user_info" );
xmlSerializer.setTypeHintsEnabled( false );
String xml = xmlSerializer.write(json);
System.out.println( "json--->xml \n" + xml);
}

 

question4:xml格式的字符串怎么转换为json格式的字符串?

?
1
2
3
4
5
6
public static void xmlToJSON(){
  System.out.println( "xml字符串转json字符串" );
  String xml = "<?xml version=\".\" encoding=\"UTF-\"?><user_info><password></password><username>张三</username></user_info>" ;
  JSON json=XMLSerializer.read(xml);
  System.out.println( "xml--->json \n" +json.toString());
  }

 

question5:javabean怎么转换为json字符串?

?
1
2
3
4
5
6
7
8
public static void javaBeanToJSON() {
  System.out.println( "javabean转json字符串" );
  UserInfo userInfo = new UserInfo();
  userInfo.setUsername( "张三" );
  userInfo.setPassword( "" );
  JSONObject json = JSONObject.fromBean(userInfo);
  System.out.println( "javabean--->json \n" + json.toString());
  }

 

question6:javabean怎么转换为xml字符串?

?
1
2
3
4
5
6
7
8
9
10
public static void javaBeanToXML() {
  System.out.println( "javabean转xml字符串" );
  UserInfo userInfo = new UserInfo();
  userInfo.setUsername( "张三" );
  userInfo.setPassword( "" );
  JSONObject json = JSONObject.fromBean(userInfo);
  XMLSerializer xmlSerializer = new XMLSerializer();
  String xml = xmlSerializer.write(json, "UTF-" );
  System.out.println( "javabean--->xml \n" + xml);
  }

 

完整的JSONObject_1_3.java代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
JSONObject_1_3
  package json;
  import net.sf.json.JSON;
  import net.sf.json.JSONObject;
  import net.sf.json.xml.XMLSerializer;
  public class JSONObject__ {
  public static void javaToJSON() {
  System.out.println( "java代码封装为json字符串" );
  JSONObject jsonObj = new JSONObject();
  jsonObj.put( "username" , "张三" );
  jsonObj.put( "password" , "" );
  System.out.println( "java--->json \n" + jsonObj.toString());
  }
  public static void jsonToJAVA() {
  System.out.println( "json字符串转java代码" );
  String jsonStr = "{\"password\":\"\",\"username\":\"张三\"}" ;
  JSONObject jsonObj = JSONObject.fromString(jsonStr);
  String username = jsonObj.getString( "username" );
  String password = jsonObj.optString( "password" );
  System.out.println( "json--->java\n username=" + username
  + "\t password=" + password);
  }
  public static void jsonToXML() {
  System.out.println( "json字符串转xml字符串" );
  String jsonStr = "{\"password\":\"\",\"username\":\"张三\"}" ;
  JSONObject json = JSONObject.fromString(jsonStr);
  XMLSerializer xmlSerializer = new XMLSerializer();
  xmlSerializer.setRootName( "user_info" );
  xmlSerializer.setTypeHintsEnabled( false );
  String xml = xmlSerializer.write(json);
  System.out.println( "json--->xml \n" + xml);
  }
  public static void javaBeanToJSON() {
  System.out.println( "javabean转json字符串" );
  UserInfo userInfo = new UserInfo();
  userInfo.setUsername( "张三" );
  userInfo.setPassword( "" );
  JSONObject json = JSONObject.fromBean(userInfo);
  System.out.println( "javabean--->json \n" + json.toString());
  }
  public static void javaBeanToXML() {
  System.out.println( "javabean转xml字符串" );
  UserInfo userInfo = new UserInfo();
  userInfo.setUsername( "张三" );
  userInfo.setPassword( "" );
  JSONObject json = JSONObject.fromBean(userInfo);
  XMLSerializer xmlSerializer = new XMLSerializer();
  String xml = xmlSerializer.write(json, "UTF-" );
  System.out.println( "javabean--->xml \n" + xml);
  }
  public static void xmlToJSON(){
  System.out.println( "xml字符串转json字符串" );
  String xml = "<?xml version=\".\" encoding=\"UTF-\"?><user_info><password></password><username>张三</username></user_info>" ;
  JSON json=XMLSerializer.read(xml);
  System.out.println( "xml--->json \n" +json.toString());
  }
  public static void main(String args[]) {
  // javaToJSON();
  // jsonToJAVA();
  // jsonToXML();
  // javaBeanToJSON();
  // javaBeanToXML();
  xmlToJSON();
  }
  }

完整的UserInfo.java代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
UserInfo
  package json;
  public class UserInfo {
  public String username;
  public String password;
  public String getUsername() {
  return username;
  }
  public void setUsername(String username) {
  this .username = username;
  }
  public String getPassword() {
  return password;
  }
  public void setPassword(String password) {
  this .password = password;
  }
  }

result

代码和运行结果都已经贴在每个问题的后面,运行时直接用main方法分别对每个方法运行即可看到测试效果。

note.txt是报的对应的错误及解决方法,也从另一个方面说明为什么需要导入前面提到的jar包;

note.txt文件内容如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

?
1
2
3
4
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

?
1
2
3
4
5
6
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

?
1
2
3
4
5
6
7
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

?
1
2
3
4
5
6
7
8
9
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

?
1
2
3
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日志问题

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JSONObject必包的Jar包及json生成的简单案例 所有commons包的网址: http://commons.apache.org/index.html 组装和解析JSONObjectJson字符串,共需要下面六个包: 1、json-lib 2、commons-beanutils 3、commons-collections 4、commons-lang 5、commons-logging 6、ezmorph 第零个包: json-lib-2.4-jdk15.jar http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-2.4/ 下载地址:http://nchc.dl.sourceforge.net/project/json-lib/json-lib/json-lib-2.4/json-lib-2.4-jdk15.jar 第一个包: commons-beanutils-1.9.2.jar http://commons.apache.org/proper/commons-beanutils/download_beanutils.cgi 下载地址:http://mirrors.cnnic.cn/apache//commons/beanutils/binaries/commons-beanutils-1.9.2-bin.zip 第二个包: (注:此包不可用,改用旧包) commons-collections4-4.0.jar http://commons.apache.org/proper/commons-collections/download_collections.cgi 下载地址:http://apache.dataguru.cn//commons/collections/binaries/commons-collections4-4.0-bin.zip (注:此包可用,低版本的包稳定性更高) commons-collections-3.2.1.jar http://commons.apache.org/proper/commons-collections/download_collections.cgi 下载地址:http://mirrors.hust.edu.cn/apache//commons/collections/binaries/commons-collections-3.2.1-bin.zip 第三个包: (注:此包不可用,会造成程序出错,改用旧包) commons-lang3-3.3.2.jar http://commons.apache.org/proper/commons-lang/download_lang.cgi 下载地址:http://apache.dataguru.cn//commons/lang/binaries/commons-lang3-3.3.2-bin.zip (注:此包可用,低版本的包稳定性更高) commons-lang-2.6-bin http://commons.apache.org/proper/commons-lang/download_lang.cgi?Preferred=http%3A%2F%2Fapache.dataguru.cn%2F 下载地址:http://apache.dataguru.cn//commons/lang/binaries/commons-lang-2.6-bin.zip 第四个包: commons-logging-1.1.3.jar http://commons.apache.org/proper/commons-logging/download_logging.cgi 下载地址:http://apache.dataguru.cn//commons/logging/binaries/commons-logging-1.1.3-bin.zip 第五个包: ezmorph-1.0.2.jar http://ezmorph.sourceforge.net/ http://sourceforge.net/projects/ezmorph/files/ezmorph/ 下载地址:http://nchc.dl.sourceforge.net/project/ezmorph/ezmorph/ezmorph-1.0.6/ezmorph-1.0.6.jar

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值