用到开源框架:net.sf.json
须有以下包
json-lib 下载http://json-lib.sourceforge.net/
依赖以下包:
ezmorph-1.0.6.jar(java对象转换工具) 下载 http://ezmorph.sourceforge.net/
commons-collections-3.2.jar、commons-beanutils-1.7.0.jar、commons-lang-2.5.jar、commons-logging-1.0.4.jar
以上为apache commons组织开源工具包 下载 http://commons.apache.org/
如要进行xml与对象间的转换须下载 xom-1.2.6.jar(xml解析工具) 下载http://www.xom.nu/
我们要用到的类主要为以下几个类
JSONObject --此类可将java对象除数组(这里的数组包括collection)转换为JSON
调用其 fromObject(Ojbect obj) 方法
JSONArray --此类可将java数组及集合collection转换为JSON
调用其 fromObject(Ojbect obj) 方法
JSONSerializer -- 此类为以上两者的综合
调用其 toJSON(Object obj)方法
另外XMLSerializer类可将xml转换为JSON可直接从文件读取转换,用到以下几个方法
read(String xml)、readFromFile(File file)、readFromFile(String filePath)
以下为本人测试用例:
package com.test.json; public class Object1 { private String name; private String password; public Object1() { } public Object1(String name, String password) { super(); this.name = name; this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
package com.test.json; import java.io.File; import java.util.ArrayList; import java.util.List; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JSONSerializer; import net.sf.json.xml.XMLSerializer; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub List<Object1> l = new ArrayList<Object1>(); l.add(new Object1("pan", "456")); l.add(new Object1("7868", "45ddf6")); l.add(new Object1("patreern", "45ert6")); l.add(new Object1("pa34dsfn", "4453456")); String fromOjbect = JSONObject.fromObject(new Object1("sdf", "13221")) .toString(); // System.out.println(fromOjbect); String formIterable = JSONArray.fromObject(l).toString(); // System.out.println(formIterable); System.out.println(JSONSerializer.toJSON(new Object1("pan", "456"))); XMLSerializer xmls = new XMLSerializer(); System.out.println(xmls.read("<root><e id='2'>sdf</e></root>")); System.out.println(xmls.readFromFile(new File("C:/Documents and Settings/Administrator/workspaces/MyEclipse 8.x/json/src/spring-remote.xml"))); } }
输出结果 :
{"name":"pan","password":"456"}
{"e":{"@id":"2","#text":"sdf"}}
。。。