使用JSON-LIB可以极大的简化JAVA对象转换成JSON对象所需进行的操作,更可以避免人工操作生成JSON对象字符串时带来的麻烦和误操作:
使用JSON-LIB,首先要有几个支持的包:
http://json-lib.sourceforge.net下载json-lib-1.1-jdk15.jar
commons-lang.jar、commons-logging.jar,commons-beanutils.jar 这些包可在tomcat/comon/lib下找到
EZMorph 下载地址http://ezmorph.sourceforge.net
morph-1.0.1 下载地址:http://morph.sourceforge.net
使用例子:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JSONTest {
public static void main(String[] args) {
JSONTest j = new JSONTest();
j.ObjectList2json();
}
public void ObjectList2json(){
Map map = new HashMap();
List jlist = new ArrayList();
JSONTestBean bean1 = new JSONTestBean("zhangbo","123123");
JSONTestBean bean2 = new JSONTestBean("lisi","65489");
Props props = new Props("127.0.0.1","8008");
jlist.add(bean1);
jlist.add(bean2);
map.put("Props", props);
map.put("jsonObjectList", jlist);
JSONArray jsonArray = JSONArray.fromObject(map);
System.out.println(jsonArray);
}
public void arr2json() {
boolean[] boolArray = new boolean[] { true, false, true };
JSONArray jsonArray = JSONArray.fromObject(boolArray);
System.out.println(jsonArray);
// prints [true,false,true]
}
public void list2json() {
List list = new ArrayList();
list.add("first");
list.add("second");
JSONArray jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray);
// prints ["first","second"]
}
public void createJson() {
JSONArray jsonArray = JSONArray.fromObject("['json','is','easy']");
System.out.println(jsonArray);
// prints ["json","is","easy"]
}
public void map2json() {
Map map = new HashMap();
map.put("name", "json");
map.put("bool", Boolean.TRUE);
map.put("int", new Integer(1));
map.put("arr", new String[] { "a", "b" });
map.put("func", "function(i){ return this.arr[i]; }");
JSONObject json = JSONObject.fromObject(map);
System.out.println(json);
// prints
// ["name":"json","bool":true,"int":1,"arr":["a","b"],"func":function(i){
// return this.arr[i]; }]
}
public void bean2json() {
JSONObject jsonObject = JSONObject.fromObject(new JSONTestBean("zhangbo","234234"));
System.out.println(jsonObject);
/*
* prints
* {"func1":function(i){ return this.options[i];
* },"pojoId":1,"name":"json","func2":function(i){ return
* this.options[i]; }}
*/
}
public void json2bean() {
String json = "{name=\"json2\",func1:true,pojoId:1,func2:function(a){ return a; },options:['1','2']}";
// JSONObject jb = JSONObject.fromString(json);
// JSONObject.toBean(jb, MyBean.class);
System.out.println();
}
}
其它两个测试实体Bean:
public class JSONTestBean {
private String userName;
private String password;
public JSONTestBean() {
}
public JSONTestBean(String username, String password) {
this.userName = username;
this.password = password;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
//===================================================
public class Props {
private String ip;
private String port;
public Props() {
}
public Props(String ip, String port) {
this.ip = ip;
this.port = port;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
}
使用起来很方便,有了JSON-LIB的支持,可以使开发者轻松构建起基于JSON的AJAX应用程序
附加:关于使用JSON-LIB转换带有DATE类型的对象需要额外的一些设置
JsonConfig cfg=new JsonConfig();
cfg.registerJsonValueProcessor(java.util.Date.class, new JsonValueProcessorImpl());
cfg.registerJsonValueProcessor(java.sql.Date.class, new JsonValueProcessorImpl());
JSONObject obj = JSONObject.fromObject(info,cfg);
JsonValueProcessorImpl为实现了源代码中的接口JsonValueProcessor
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
public class JsonValueProcessorImpl implements JsonValueProcessor{
private String format="yyyy-MM-dd";
public JsonValueProcessorImpl(){
}
public JsonValueProcessorImpl(String format){
this.format=format;
}
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
String[] obj={};
if(value instanceof Date[]){
SimpleDateFormat sf=new SimpleDateFormat(format);
Date[] dates=(Date[])value;
obj =new String[dates.length];
for (int i = 0; i < dates.length; i++) {
obj[i]=sf.format(dates[i]);
}
}
return obj;
}
public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
if(value instanceof Date){
String str=new SimpleDateFormat(format).format((Date)value);
return str;
}
return value.toString();
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}