用反射实现自定义Java对象转化为json工具类

  1. 传入一个object类型的对象
  2. 获取该对象的class类
  3. getFields方法获取该类的所有属性
  4. 对属性进行遍历,并且拼接成Json格式的字符串,注意:通过属性名来推断方法名
  5. 获取Method实例
  6. 通过invoke方法调用
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类进行测试

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 +
                '}';
    }
}
User user = new User(1,"tom");
String s = objectToJson(user);
System.out.println(s);

  

你可能感兴趣的:(java,json)