Chinaunix首页 | 论坛 | 博客
  • 博客访问: 26278649
  • 博文数量: 2065
  • 博客积分: 10377
  • 博客等级: 上将
  • 技术积分: 21525
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-04 17:50
文章分类

全部博文(2065)

文章存档

2012年(2)

2011年(19)

2010年(1160)

2009年(969)

2008年(153)

分类: Java

2010-01-12 10:14:25

Java操作JSON工具整理

[整理人:hkebao#126.com 整理时间:2010-1-11]

一、配置开发运行环境

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

以上包可以从

中下载到。

我下载来的第三方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 list = new ArrayList();

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对象!

 

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

一、使用JSONSerializer

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

JSONSerializer.toJSON()              

1.1     将数组与集合对象转换成JSON对象

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

JSONArray jsonArray1 = JSONArray.fromObject( boolArray );     

System.out.println(jsonArray1);

 

List list = new ArrayList();

list.add("first");

list.add("second");

JSONArray jsonArray2 = JSONArray.fromObject(list);

System.out.println(jsonArray2);

 

1.2JAVABEANMAP转换成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

1.3JSON转换成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();

       }

      

    }

}

1.4解析XMLJSON相关的

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

在网上看到大家都是这样写代码的: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下载

终于被我找到了下载的地址:

 

我下载了一个包进来: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);

    }

}

输出:

true1json

 

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

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

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

 

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

1.5XML转换成JSON

public class JSONUtils {

    public static void main(String[] args) {

       String xmlString = "s";

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

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

    }

}

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

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

 

 

(下一篇我会整理常用的JAVA操作JSONAPI工具类及文档大家可以直接使用)

待续………

阅读(1924) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-06-15 22:07:19

有的时候如果我需要调用第三方接口现在我需要传一个数组类型的数据过去的话怎么办?解决办法:将数组序列化成JSON类型再传过去。然后接收方进行一次反序列处理即可!

chinaunix网友2010-03-24 13:53:10

好啊 ·1谢谢