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

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 {

      &nbs