json-lib
- Javabean转json需要用到json-lib包,它可以把javabean转换成json串
- jar包
json-lib的核心jar包有:
json-lib.jar
json-lib的依赖jar包有:
commons-lang.jar
commons-beanutils.jar
commons-logging.jar
commons-collections.jar
ezmorph.jar
- 核心类
JSONObject json = JSONObject.fromObject(person);//把对象转换成JSONObject对象
JSONArray jsonArray = JSONObject.fromObject(list):把list转换成JSONArray对象
示例
- User类
package com.yuzk.test;
/**
* User类
* @author yuzk
*
*/
public class User {
private String name;
private Integer age;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + ", address=" + address
+ "]";
}
}
- 测试类
public class test { @Test public void testJson(){ User user = new User(); user.setName("张三"); user.setAge(24); user.setAddress("火星"); System.out.println(beanToJson(user)); } public String beanToJson(Object bean) { JSONObject json = JSONObject.fromObject(bean); return json.toString(); }
- 但是如果从数据库查数据,有日期类型,上述方法不能把Javabean转换为json,需要修改方法,加两行代码
public String beanToJson2(Object bean) { // 用来解决date类型不能转json的方法 JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor()); JSONObject json = JSONObject.fromObject(bean,jsonConfig); return json.toString(); }