使用java 反射,对类中成员变量赋值.将Json对像转为Java对像

来源:互联网 发布:淘宝库存手表 编辑:程序博客网 时间:2024/06/06 08:21

面临的麻烦,

Android 开发中经常需要与Intenet通信获取数据 ,中间交换格式,大家都喜欢Json, 如何将Json对像转为Java的对像? 一个个属性来解析可以实现,但对我来说这样做太土了.

通过Java的反射可以很方便,高效,易读的实现


先看一个Json对像

{"content":[{"level":1,"status":"2","businessLicence":true,"hygieneLicence":true,"note":"note1","enterprise":"free","principal":"老韩","phone":"13366350377","time":1380862998588, "address":"bj aa","latitude":38.112,"longitude":116.002   },{"level":2,"status":"3","businessLicence":false,"hygieneLicence":false,"note":"note22222222222222222222222","enterprise":"鹏程万里","principal":"韩工","phone":"13366350377","time":1380962998588, "address":"bj aa","latitude":38.112,"longitude":116.002},{"level":3,"status":"4","businessLicence":true,"hygieneLicence":false,"note":"海天3 note333333333333333333333333333","enterprise":"csdn","principal":"韩工","phone":"13366350377","time":1380943998588, "address":"bj aa","latitude":38.112,"longitude":116.002}]}

一个Json对像


对应的 Java对像

public class Content {private int level;private String status;private boolean businessLicence;private boolean hygieneLicence;private String note;//private String enterprise;private String principal;private long time;private String address;private double latitude;private double longitude;private String phone;private final String[] properties = {"level","phone","status", "businessLicence", "hygieneLicence","note","enterprise","principal","time","address","latitude","longitude"};public Content() {time = System.currentTimeMillis();init();}public Content(JSONObject jObj) {if (null == jObj) {time = System.currentTimeMillis();return;}init();try {fromJSONObject(jObj);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}public String getCategory() {// TODO Auto-generated method stubreturn category;}public JSONObject toJSONObject() {// TODO Auto-generated method stubreturn null;}public Content fromJSONObject(JSONObject jObj) throws JSONException {if (null == jObj)return null;Object obj;for (String property : properties) {if (jObj.has(property)) {obj = jObj.get(property);// 方法1:// 比较文明,调用类的set 方法进行赋值.setProperty("set" + property, obj);// 方法2:// 直接对属性赋值,有点野蛮// this.getClass().getDeclaredField(property).set(property, v);// Field field = this.getClass().getDeclaredField(property);// boolean accessible = field.isAccessible();// field.setAccessible(true);// field.set(this, v);// field.setAccessible(accessible);}}return this;}/** 下面是常用的老土的方法,全是体力活 : *  */public Content fromJSONObject2(JSONObject jObj) throws JSONException {if (null == jObj)return null;if (jObj.has("level")) {level = jObj.getInt("level");}if (jObj.has("status")) {status = jObj.getString("status");}if (jObj.has("businessLicence")) {businessLicence = jObj.getBoolean("businessLicence");}if (jObj.has("hygieneLicence")) {hygieneLicence = jObj.getBoolean("hygieneLicence");}if (jObj.has("note")) {note = jObj.getString("note");}if (jObj.has("enterprise")) {enterprise = jObj.getString("enterprise");}if (jObj.has("principal")) {principal = jObj.getString("principal");}if (jObj.has("time")) {time = jObj.getLong("time");}if (jObj.has("address")) {address = jObj.getString("address");}if (jObj.has("latitude")) {latitude = jObj.getDouble("latitude");}if (jObj.has("longitude")) {longitude = jObj.getDouble("longitude");}return this;}public int getLevel() {return level;}public void setLevel(int level) {this.level = level;}public String getStatus() {return status;}public void setStatus(String status) {this.status = status;}public boolean isBusinessLicence() {return businessLicence;}public void setBusinessLicence(boolean businessLicence) {this.businessLicence = businessLicence;}public boolean isHygieneLicence() {return hygieneLicence;}public void setHygieneLicence(boolean hygieneLicence) {this.hygieneLicence = hygieneLicence;}public String getNote() {return note;}public void setNote(String note) {this.note = note;}public String getEnterprise() {return enterprise;}public void setEnterprise(String enterprise) {this.enterprise = enterprise;}public String getPrincipal() {return principal;}public void setPrincipal(String principal) {this.principal = principal;}public long getTime() {return time;}public void setTime(long time) {this.time = time;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public double getLatitude() {return latitude;}public void setLatitude(double latitude) {this.latitude = latitude;}public double getLongitude() {return longitude;}public void setLongitude(double longitude) {this.longitude = longitude;}boolean isMe(String category) {this.category.equals(category);}public String getContent() {return note;}public Drawable getIcon() {return null;}String getVillage() {return null;}public String getCell() {return null;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}// 反射代码,final private Map<String, Method> methodMap = new HashMap<String, Method>();// 以set开始的方法的map// 可以直接获取需要的set方法.protected void init() {Class<?> userClass = this.getClass();// Class.forName(this.getClass()); 加载类Method[] methods = userClass.getDeclaredMethods();// 获得类的方法集合for (int i = 0; i < methods.length; i++) {if (methods[i].getName().startsWith("set")) {methodMap.put(methods[i].getName().toLowerCase(), methods[i]);}}}protected void setProperty(String property, Object v) {Method method = methodMap.get(property.toLowerCase());try {method.invoke(this, v);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}



对通上述的代码,可以明显发现,使用Java 反射带来的好处


1 0
原创粉丝点击