根据Java实体类生成JSON字符串

时间:2024-02-24 18:08:23
public static String getJSONStringFromJavaBean(Class<? extends Object> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        StringBuffer stb = new StringBuffer("{");
        for (int i = 0; i < fields.length; i++) {
            try {
                Field field = fields[i];
                field.setAccessible(true);
                String name = field.getName();
                stb.append("\"").append(name).append("\"").append(":\"\"").append(",");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        int i = stb.lastIndexOf(",");
        return stb.substring(0,i)+"}";
}