日期:2014-05-16  浏览次数:20395 次

JSONOBJ 转换对象

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.json.JSONObject;


public class JsonToObject {
public static void main(String[] args) throws Exception {
?
?JSONObject obj = new JSONObject();
?obj.put("id", 1);
?obj.put("name","zx");
?obj.put("date",new Date());
?obj.put("size",10);
?obj.put("sum",20.5);
?JsonToObject? j = new JsonToObject();

//net.jsf.json 包JSONobjct 自带的
?Object bean = JSONObject.toBean(obj, Student.class);
?

//自己封装的jsonObj转换 pojo
//?j.fromJsonToJava(obj, Student.class,"yyyy-MM-dd HH:mm:ss");
?
}

private Object fromJsonToJava(JSONObject json,Class pojo,String dateFormat) throws Exception{
?????????? // 首先得到pojo所定义的字段
?????????? Field [] fields = pojo.getDeclaredFields();
?????????? // 根据传入的Class动态生成pojo对象
?????????? Object obj = pojo.newInstance();
?????????? for(Field field: fields){
?????????????? // 设置字段可访问(必须,否则报错)
?????????????? field.setAccessible(true);
????????????? // 得到字段的属性名
????????????? String name = field.getName();
????????????? // 这一段的作用是如果字段在JSONObject中不存在会抛出异常,如果出异常,则跳过。
????????????? try{
????????????????????? json.get(name);
????????????? }catch(Exception ex){
????????????????? continue;
????????????? }
????????????? if(json.get(name) != null && !"".equals(json.getString(name))){
????????????????? // 根据字段的类型将值转化为相应的类型,并设置到生成的对象中。
????????????????? if(field.getType().equals(Long.class) || field.getType().equals(long.class)){
????????????????????? field.set(obj, Long.parseLong(json.getString(name)));
????????????????? }else if(field.getType().equals(String.class)){
????????????????????? field.set(obj, json.getString(name));
????????????????? } else if(field.getType().equals(Double.class) || field.getType().equals(double.class)){
????????????????????? field.set(obj, Double.parseDouble(json.getString(name)));
????????????????? } else if(field.getType().equals(Integer.class) || field.getType().equals(int.class)){
??????????????