JSON与XML两者目前在数据交互方面都有很高的使用率,随着现在SOA的兴起,异构系统的整合地位相应提高,本篇文章主要介绍JSON与JAVA对象之间的相互转换。
一、对普通类型的JSON模式的转换
一般JSON为最普通的String类型组成,没有其它Data或Object等这种特殊类形,具体例子如下:
JSON:
jsonString = {"name":"jack","sex":"men","age":23};
JAVA BEAN:
public class Person{
private String name;
private String sex;
private Integer age;
...omit get or set method...
}
现在如果我们想把上面的JSON格式转为Java bean类,常用方法为:
jsonObject = JSONObject.fromObject(jsonString);
Object results = JSONObject.toBean(jsonObject, Person.class);
这样返回来的数据就为Person类型的实例,在JSONObject.toBean();的方法签名中第一个参数为jsonObject对象,第二个参数为要转换后的JAVA BEAN的class类。
二、对有Date或List类型的转换
JSON:
jsonString = {"name":"jack","sex":"women","birthday":"2010-06-12","address":[{"officeAttr":"NEWS RORK","HomeAttr":"beijing"},{"officeAttr":"taiyuan","HomeAttr":"hongkong"}]};
JAVA BEAN:
public class Person{
private String name;
private String sex;
private Date birthday;
private List<Address> address;
...omit get or set method...
}
public class Address{
private String officeAttr;
private String homeAttr;
...omit get or set method...
}
现在如果我们想把上面的JSON格式转为Java bean类,常用方法为:
JSONUtils.getMorpherRegistry().registerMorpher(new JsonDateValueProcessor(new String[] { "yyyy-MM-dd","yyyy-MM-dd HH:mm:ss" }));
Map<String,Class> map = new HashMap<String,Class>();
map.put("address",Address.class); //map中的key值为json中list的key值,value为Address的class类对象
jsonObject = JSONObject.fromObject(jsonString);
Object results = JSONObject.toBean(jsonObject, Person.class, map);
public class JsonDateValueProcessor implements JsonValueProcessor {
private String format = "yyyy-MM-dd HH:mm:ss";
public JsonDateValueProcessor() {
}
public JsonDateValueProcessor(String format) {
this.format = format;
}
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
return process(value, jsonConfig);
}
public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
return process(value, jsonConfig);
}
private Object process( Object value, JsonConfig jsonConfig ) {
if (value instanceof Date) {
String str = new SimpleDateFormat(format).format((Date) value);
return str;
}
return value == null ? null : value.toString();
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}