level 9
import java.lang.reflect.Method;
import org.json.JSONObject;
import org.json.JSONException;
import java.lang.reflect.InvocationTargetException;
public class Gson {
public static String toJson(Object obj) {
try {
Class clazz = obj.getClass();
Method[] method = clazz.getMethods();
JSONObject json = new JSONObject();
for (Method m : method) {
if (!m.getName().equals("getClass") && m.getName().startsWith("get")) {
json.put(m.getName().replaceAll("^get", "").toLowerCase(), clazz.getMethod(m.getName()).invoke(obj));
}
}
return json.toString();
} catch (Exception e) {
return e.toString();
}
}
public static Object fromJson(String json, Object obj) {
try {
Class clazz = Class.forName(obj.toString().replaceAll("^class ", ""));
Object result = clazz.newInstance();
Method[] method = clazz.getMethods();
for (Method m : method) {
if (m.getName().startsWith("set")) {
String type = m.getParameterTypes()[0].toString();
String name = m.getName();
if (type.equals("int")) {
Method set = clazz.getMethod(name, int.class);
int i = new JSONObject(json).getInt(name.replaceAll("^set", "").toLowerCase());
set.invoke(result, i);
} else if (type.endsWith("String")) {
Method set = clazz.getMethod(name, String.class);
String i = new JSONObject(json).getString(name.replaceAll("^set", "").toLowerCase());
set.invoke(result, i);
}
}
}
return result;
} catch (Exception e) {
return null;
}
}
}
没错,这是自己盗版的一个gson
2017年06月24日 15点06分
4