读书人

Android中透过annotation实现java对象

发布时间: 2013-10-29 12:07:57 作者: rapoo

Android中通过annotation实现java对象和json的转换

第一步:定义一个annotation类

@Target(ElementType.FIELD)

@Retention(RetentionPolicy.RUNTIME)

public @interface JSONValue {

public String tag() default "";

}

第二步:封装转换方法

public class JSONConverter {

/* * 将json字符串(如:"{'id':123,'name':'张三'}")转换成对象 */

public static void fromJson(String json_string, Object o) {

try {

JSONObject jo = new JSONObject(json_string);

Field[] fields = o.getClass().getFields();

for (Field f : fields) {

if (f.isAnnotationPresent(JSONValue.class)) {

JSONValue jv = f.getAnnotation(JSONValue.class);

String tag = jv.tag();

if (tag.length() > 0) {

if (f.getType().getSimpleName().equals("int")) {

f.setInt(o, jo.optInt(tag));

} else {

f.set(o, jo.optString(tag));

}

}

}

}

MyObject mo = (MyObject) o;System.out.println("o--->" + mo.getmId());

System.out.println("o--name->" + mo.getmName());

} catch (Exception e) {

// TODO Auto-generated catch blocke.

printStackTrace();

}

}

/* * 将对象转换成json */

public static String toJSon(Object o) throws Exception {

JSONObject jo = new JSONObject();

Field[] fields = o.getClass().getFields();

for (Field f : fields) {

if (f.isAnnotationPresent(JSONValue.class)) {

JSONValue jv = f.getAnnotation(JSONValue.class);

String tag = jv.tag();// System.out.println("tag--->>>"+tag);

if (tag.length() > 0) {

// System.out.println("f.getType().getSimpleName()-->"+f.getType().getSimpleName());

if (f.getType().getSimpleName().equals("int")) {

System.out.println("f.getInt(o)--->" + f.getInt(o));

jo.put(tag, f.getInt(o));

} else {

Object v = f.get(o);

if (v != null)jo.put(tag, v);

}

}

}

}

System.out.println("tojson--->" + jo.toString());return jo.toString();

}

}

第三步:创建自己的类并使用annotation

public class MyObject {

@JSONValue(tag = "id")

public int mId;

@JSONValue(tag = "name")

public String mName;

public int getmId() {

return mId;

}

public void setmId(int mId) {

this.mId = mId;

}

public String getmName() {

return mName;

}

public void setmName(String mName) {

this.mName = mName;

}

}

第四步:调用

public void onClick(View v) {

// TODO Auto-generated method stub

MyObject mo = new MyObject(); //对象转json

mo.mId = 100;

mo.mName = "xxfdse";

try {

JSONConverter.toJSon(mo);

} catch (Exception e) {

e.printStackTrace();

}

//====================================================

String json_string = "{'id':123,'name':'张三'}";//json转对象

MyObject o = new MyObject();

JSONConverter.fromJson(json_string, o);

}

读书人网 >JavaScript

热点推荐