第一步:定義一個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);
}