Java操作JSON工具整理

本文详细介绍了如何使用JSON与XML之间的转换技术,包括将数组、集合、JavaBean与Map对象转换为JSON对象,以及将JSON对象转换回JavaBean对象。同时,文章还演示了如何将JSON数据格式转换为XML格式,并提供了相应的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、配置开发运行环境

Json必需的包

commons-httpclient-3.1.jar
commons-lang-2.4.jar
commons-logging-1.1.1.jar
json-lib-2.2.3-jdk13.jar
ezmorph-1.0.6.jar
commons-collections-3.2.1.jar

xom-1.0b3.jar

commons-beanutils.jar

以上包可以从

http://commons.apache.org/index.html

http://json-lib.sourceforge.net/

http://ezmorph.sourceforge.net/

http://morph.sourceforge.net/

http://www.docjar.com/

中下载到。

我下载来的第三方JAR包统一存放在:F:\Java\opensourcejar\json-java 目录下面

我已经打包上传到我的博客:http://blogimg.chinaunix.net/blog/upfile2/100111174806.rar

有需要的可以上我的博客去下载下来使用!

(目前我博客上面的这个打包JAR是最全的。全部相关的JAR都包含进来了)

二、将这些第三方的JAR包导入本地项目

配置好当前的应用程序项目环境。

三、具体的应用举例

3.1 将数组转换成JSON数组

boolean[] boolArray = new boolean[]{true,false,true}; 数组

JSONArray jsonArray1 = JSONArray.fromObject( boolArray ); JSON对象

3.2 将List类型转换成JSON数组

List<String> list = new ArrayList<String>();

list.add("first");

list.add("second");

JSONArray jsonArray2 = JSONArray.fromObject(list);

3.3 将其它类型的数据转换成JSON对象

Map map = new HashMap();

map.put("name","json");

map.put("bool", Boolean.TRUE);

map.put("int", new Integer(1));

map.put("func", "function(i){return this.arr[i]; }");

JSONObject json = JSONObject.fromObject(map); 得到对象

System.out.println(json);

输出:

{"int":1,"name":"json","func":function(i){return this.arr[i]; },"bool":true}

即一个JSON对象!

以下内容是学习自其官网的教程

<!--[if !supportLists]-->一、<!--[endif]-->使用JSONSerializer

通过这个方法能够将JAVA对象转变成JSON对象。将JAVA对象转换成JSON对象的方法:

JSONSerializer.toJSON()

<!--[if !supportLists]-->1.1 <!--[endif]-->将数组与集合对象转换成JSON对象

boolean[] boolArray = new boolean[]{true,false,true};

JSONArray jsonArray1 = JSONArray.fromObject( boolArray );

System.out.println(jsonArray1);

List<String> list = new ArrayList<String>();

list.add("first");

list.add("second");

JSONArray jsonArray2 = JSONArray.fromObject(list);

System.out.println(jsonArray2);

<!--[if !supportLists]-->1.2<!--[endif]-->从JAVABEAN与MAP转换成JSON对象

Map map = new HashMap();

map.put("name","json");

map.put("bool", Boolean.TRUE);

map.put("int", new Integer(1));

map.put("func", "function(i){return this.arr[i]; }");

JSONObject json = JSONObject.fromObject(map);

System.out.println(json);

现在面对的问题就是如何将一个JAVABEAN对象转换成JSON对象

报了一个异常:net.sf.json.JSONException: java.lang.NoSuchMethodException: Property 'name' has no getter method

解决办法:将我们的BEAN定义为Public类型的。就可以解决了!

代码如下:

Bean.java代码

package json.utils;

import net.sf.json.JSONFunction;

public class Bean{

private String name = "json";

private int pojoId = 1;

private char[] options = new char[]{'a','f'};

private String func1 = "function(i){ return this.options[i]; }";

private JSONFunction func2 = new JSONFunction(new String[]{"i"},"return this.options[i];");

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getPojoId() {

return pojoId;

}

public void setPojoId(int pojoId) {

this.pojoId = pojoId;

}

public char[] getOptions() {

return options;

}

public void setOptions(char[] options) {

this.options = options;

}

public String getFunc1() {

return func1;

}

public void setFunc1(String func1) {

this.func1 = func1;

}

public JSONFunction getFunc2() {

return func2;

}

public void setFunc2(JSONFunction func2) {

this.func2 = func2;

}

}

转换的JAVA代码如下:

public static void main(String[] args) {

JSONObject jsonObject = JSONObject.fromObject(new Bean());

System.out.println(jsonObject);

}

输出:

{"func1":function(i){ return this.options[i]; },"func2":function(i){ return this.options[i]; },"name":"json","options":["a","f"],"pojoId":1}

注意了!如果没有声明为public类型的话就会报异常!其中官方的示例也没有加public可能有bug!

<!--[if !supportLists]-->1.3<!--[endif]-->将JSON转换成JAVABEAN对象

public class JSONUtils {

public static void main(String[] args) {

//JSONObject jsonObject = JSONObject.fromObject(new Bean());

//System.out.println(jsonObject);

String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}"; //定义一个JSON对象

JSONObject jsonObject = JSONObject.fromObject( json );

Object bean = JSONObject.toBean( jsonObject ); //转变成BEAN

System.out.println(jsonObject.get("name"));//JSON取值

try {

System.out.println(PropertyUtils.getProperty(bean, "name"));//BEAN中取值的方法

} catch (IllegalAccessException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (InvocationTargetException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (NoSuchMethodException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

<!--[if !supportLists]-->1.4<!--[endif]-->解析XML与JSON相关的

一开始的时候总是会遇到一个错误。

在网上看到大家都是这样写代码的:String xml = XMLSerializer.write( json );

我就奇怪了这个XMLSerializer 类到底在哪里呢?

奇了怪了。还是到它的官网查吧

官网的代码是这样写的:

public static void main(String[] args) {

JSONObject json = JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");

String xml = new XMLSerializer().write( json );

System.out.println(xml);

}

不过不幸的是报了这个异常:

Exception in thread "main" java.lang.NoClassDefFoundError: nu/xom/Serializer
at com.jason.test.JasonToXml.main(JasonToXml.java:10)

有了异常之后就看下我是如何解决的

在GOOGLE上面搜索一下这个问题关键字:nu.xom.Serializer下载

终于被我找到了下载的地址:http://repo1.maven.org/maven2/xom/xom/1.0b3/

我下载了一个包进来:xom-1.0b3.jar

然后我导入到我的项目中。成功

示例如下的代码:

public class JSONUtils {

public static void main(String[] args) {

JSONObject json = JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");

String xml = new XMLSerializer().write( json );

System.out.println(xml);

}

}

输出:

<?xml version="1.0" encoding="UTF-8"?>

<o><bool type="boolean">true</bool><int type="number">1</int><name type="string">json</name></o>

我将全部相关的包再整理了一份放在:我的博客上面了!大家可以一块下载下来

地址是:http://blogimg.chinaunix.net/blog/upfile2/100112100105.rar

将全部相关的包一并打包下载吧!这样你的程序就不会出现什么缺少JAR包的了!

以上是如何将JSON数据格式写成XML格式。现在看一下如何将一段XML写成JSON

<!--[if !supportLists]-->1.5<!--[endif]-->将XML转换成JSON

public class JSONUtils {

public static void main(String[] args) {

String xmlString = "<xml><resin>s</resin></xml>";

JSONObject jsonArray = (JSONObject) new XMLSerializer().read(xmlString);

System.out.println( jsonArray.get("resin") );

}

}

因为我查了一下API发现 new XMLSerializer().read(xml)

返回的是一个JSON对象。而JSONObject与JSONArray都是JSON的子类。所以可以利用多态的思想直接使用它!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值