import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.json.JSONObject;
/**
-
将对象转换为JSON对象
-
@param value
-
对象
-
@return JSONObject
*/
public class test {
public static void main(String[] args) {
aaa aaa=new aaa();
JSONObject obj=json(aaa);
System.out.println(“obj:”+obj);}
public static JSONObject json(Object object) {
JSONObject obj=new JSONObject();
try {
//获取实体类的所有属性,返回Field数组
Field[] field = object.getClass().getDeclaredFields();
String[] objectName = new String[field.length];
String[] objectType = new String[field.length];
for(int j=0 ; j<field.length ; j++){
String type = field[j].getGenericType().toString();
String name = field[j].getName();
String mname = getMethodName(name);
if (type.indexOf(“class”)>-1&&type.indexOf(“java.lang.String”)==-1 ) { //如果type是类类型,则前面包含"class ",后面跟类名
System.out.println(“a”+name);
try {
Method m = object.getClass().getMethod(“get” + mname);
Object obj1 = (Object) m.invoke(object); //调用getter方法获取属性值、获取值转换为对象
if (obj1 != null) {
Method m_id = obj1.getClass().getMethod(“getId”);
Long l_id = (Long) m_id.invoke(obj1);
if (l_id != null) {
obj.put(name, l_id);
}
}else{
obj.put(name, “”);
}
}
catch (Exception e) {}} if(type.indexOf("java.lang.String")>-1){ //如果type是类类型,则前面包含"class ",后面跟类名 try{ Method m = object.getClass().getMethod("get"+mname); String value = (String) m.invoke(object); //调用getter方法获取属性值 if(value!=null) { obj.put(name, value);}else { obj.put(name, ""); } }catch(Exception e){ } } if(type.indexOf("int")>-1){ Method m = object.getClass().getMethod("get"+name); Integer value = (Integer) m.invoke(object); obj.put(name, value); } } }catch(Exception e) { e.printStackTrace(); }
return obj;
}
private static String getMethodName(String fildeName) throws Exception{
byte[] items = fildeName.getBytes();
items[0] = (byte) ((char) items[0] - ‘a’ + ‘A’);
return new String(items);
}
}
class aaa{
private int Id;
private String name;
private String password;
private bbb bbb;
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public bbb getBbb() {
return bbb;
}
public void setBbb(bbb bbb) {
this.bbb = bbb;
}
}
class bbb{
private int Id;
private String name;
private String password;
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}