日期:2014-05-16 浏览次数:20403 次
/** * Student * * @author shanzhu * @version 1.0 2011-10-17 */ package json; import java.io.Serializable; public class Student implements Serializable { /** * */ private static final long serialVersionUID = 8424716517986346222L; private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } 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; } }
/** * json test * * @author shanzhu * @version 1.0 2011-10-17 */ package json; import json.reflect.JsonReflect; import net.sf.json.JSONObject; public class JsonText { /** * @param args */ public static void main(String[] args) { // 对象转化成json格式的 // Student student = new Student(); // student.setAge(10); // student.setId(1); // student.setName("bushyou"); // Map mapObject = (new JsonReflect<Student>(student)).Class2JsonObject(); // JSONObject jsonObject = new JSONObject(); // jsonObject.put("status", 200); // jsonObject.put("data", mapObject); // System.out.println(jsonObject.toString()); // json格式转化成对象的 String strObject = "{\"status\":200,\"data\":{\"id\":1,\"age\":10,\"name\":\"bushyou\"}}"; //生成json格式 JSONObject jsonObject1 = JSONObject.fromObject(strObject); JSONObject jsonObject2 = (JSONObject) jsonObject1.get("data"); Student student = new Student(); student = new JsonReflect<Student>(student).JsonObject2Class(jsonObject2); System.out.println(student.getName()); } }
/** * 操作json格式的基础类 * * @author shanzhu * @version 1.0 2011-10-17 */ package json.reflect; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import json.reflect.factory.IType; import json.reflect.factory.JavaTypeFactory; import net.sf.json.JSONObject; public class JsonReflect<T> { private static final String SERIAL_VERSION_UID = "serialVersionUID"; public Class classType; private T t; public JsonReflect(T t) { this.t = t; classType = t.getClass(); } /** * 将类转化成json对象 * @return */ public Map Class2JsonObject() { Field[] fields = this.classType.getDeclaredFields(); String filedsName = ""; Object filedsValue = ""; Map map = new HashMap(); Field field = null; for (int i = 0; i < fields.length; i++) { field = fields[i]; field.setAccessible(true); filedsName = field.getName(); if (SERIAL_VERSION_UID.equalsIgnoreCase(filedsName)) { continue; } try { filedsValue = field.get(t); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } map.put(filedsName,filedsValue); field = null; } return map; } public T JsonObject2Class(JSONObject jsonObject){ T t = null; Object obj = null; try { obj = classType.newInstance(); } catch (InstantiationException e1) { // TODO