反射--简单模拟,有不完善的地方还请大家谅解
public String ObjToJson(Object Obj) {
String JsonObjString = "";
// ------------------------------------ 取得本类的全部属性和getters
Field[] field = Obj.getClass().getDeclaredFields();
Method method = null;
for (int i = 0; i < field.length; i++) {
try {
method = Obj.getClass().getMethod(
"get"
+ field[i].getName().substring(0, 1)
.toUpperCase()
+ field[i].getName().substring(1));
JsonObjString += "'" + field[i].getName() + "':'"
+ method.invoke(Obj) + "',";
} catch (Exception e) {
e.printStackTrace();
}
}
return "{" + JsonObjString.substring(0, JsonObjString.length() - 1) + "}";
}
public String ListoJson(List<?>list){
String JsonListString="";
for (Object object : list) {
JsonListString+=this.ObjToJson(object)+",";
}
return "["+JsonListString.substring(0,JsonListString.length()-1)+"]";
}
输出结果:[{'name':'msz','age':'1'},{'name':'msz','age':'1'}]