- 传入一个object类型的对象
- 获取该对象的class类
- getFields方法获取该类的所有属性
- 对属性进行遍历,并且拼接成Json格式的字符串,注意:通过属性名来推断方法名
- 获取Method实例
- 通过invoke方法调用
java
public static String objectToJsonUtil(Object object) throws Exception {
String s = "{";
Class c = object.getClass();
Field[] fields = c.getFields();
for(Field f : fields){
String name = "get"+String.valueOf(f.getName().charAt(0)).toUpperCase()+
f.getName().substring(1);
Method method = c.getMethod(name);
s+=f.getName()+":"+method.invoke(object)+",";
}
s=s.substring(0,s.length()-1);
s+="}";
return s;
}
以User类进行测试
java
public class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public User(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", id=" + id +
'}';
}
}
java
User user = new User(1,"tom");
String s = objectToJson(user);
System.out.println(s);