使用java反射简单模拟json数据

在做项目时,公司催进度,往往是接口都还没有写好,产品就开始要各种演示版本,为了演示的时候能展示数据,往往就需要客户端自己模拟数据,以达到展示的目的,这是苦逼,我就上网百度了一下,再发挥自己的聪明才智,写了一个模拟json数据的转化工具类,方便大家自举。

public class JsonUtil {

    public static String class2json(Object obj) {
        // 通过反射获取到类
        Class clazz = obj.getClass();
        // 获取类中所有的字段
        Field[] fields = clazz.getDeclaredFields();

        StringBuffer buffer = new StringBuffer();
        buffer.append("{");
        // 设置setAccessible方法能获取到类中的私有属性和方法
        Field.setAccessible(fields, true);
        for (Field field : fields) {

            try {

                Object object = field.get(obj);

                // 获取到该属性对应类型名称
                String fieldName = field.getType().getSimpleName();

                // 如果该属性的值为空
                if (object == null) {

                    // 根据类型判断追加的值
                    if (fieldName.equals("String")) {
                        buffer.append("\"" + field.getName() + "\":\"\",");
                    } else if (fieldName.equals("Boolean")
                            || fieldName.equals("Integer")
                            || fieldName.equals("Double")
                            || fieldName.equals("Float")
                            || fieldName.equals("Long")) {

                        buffer.append("\"" + field.getName() + "\":0,");
                    }

                    else {
                        buffer.append("\"" + field.getName() + "\":null,");
                    }

                } else {

                    // 获取到该属性的值对应的类
                    Class fieldclass = object.getClass();
                    String simpleName = fieldclass.getSimpleName();

                    if (simpleName.equals("String")) {

                        buffer.append("\"" + field.getName() + "\":\""
                                + field.get(obj) + "\",");

                    } else if (simpleName.equals("Boolean")
                            || simpleName.equals("Integer")
                            || simpleName.equals("Double")
                            || simpleName.equals("Float")
                            || simpleName.equals("Long")) {

                        buffer.append("\"" + field.getName() + "\":"
                                + field.get(obj) + ",");

                    } else if (simpleName.equals("Date")) {

                        Date date = (Date) object;
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                                "yyyy-MM-dd hh:mm:ss");
                        String simdate = simpleDateFormat.format(date);
                        buffer.append("\"" + field.getName() + "\":\""
                                + simdate + "\",");

                    } else if (simpleName.equals("ArrayList")
                            || simpleName.equals("LinkedList")) {
                        // 将获取到的值强转为list集合
                        List list = (List) object;
                        buffer.append("\"" + field.getName() + "\":[");

                        // 执行listTojson方法将获取到的list转为json格式
                        buffer = listTojson(buffer, list).append("]");
                    } else {

                        buffer = beanTojson(object, buffer).append(",");
                    }
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        buffer = new StringBuffer(buffer.substring(0, buffer.length() - 1));
        buffer.append("}");

        return buffer.toString();
    }

    public static StringBuffer listTojson(StringBuffer buffer, List list)
            throws IllegalArgumentException, IllegalAccessException {

        // 遍历传过来的list数组
        for (Object object : list) {

            // 判断遍历出的值是否为空
            if (object == null) {
                buffer.append(",");
            } else {

                Class class1 = object.getClass();
                String simpleName = class1.getSimpleName();

                if (simpleName.equals("String")) {

                    buffer.append("\"" + object.toString() + "\",");
                } else if (simpleName.equals("Boolean")
                        || simpleName.equals("Integer")
                        || simpleName.equals("Double")
                        || simpleName.equals("Float")
                        || simpleName.equals("Long")) {

                    buffer.append("" + object.toString() + ",");
                } else if (simpleName.equals("Date")) {
                    Date date = (Date) object;
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                            "yyyy-MM-dd hh:mm:ss");
                    String simdate = simpleDateFormat.format(date);
                    buffer.append("" + simdate + ",");
                } else {

                    Class class2 = object.getClass();
                    Field[] fields = class2.getDeclaredFields();
                    Field.setAccessible(fields, true);
                    buffer.append("{");
                    // 遍历对象中的所有字段获取字段值和字段名称拼成json字符串
                    for (Field field : fields) {

                        Object fieldobj = field.get(object);
                        String fieldName = field.getType().getSimpleName();

                        if (fieldobj == null) {

                            if (fieldName.equals("String")) {
                                buffer.append("\"" + field.getName()
                                        + "\":\"\",");
                            }

                            else {
                                buffer.append("\"" + field.getName()
                                        + "\":null,");
                            }

                        }

                        else {

                            String fsimpleName = fieldobj.getClass()
                                    .getSimpleName();

                            if (fsimpleName.equals("String")) {

                                buffer.append("\"" + field.getName() + "\":\""
                                        + field.get(object) + "\",");
                            } else if (fsimpleName.equals("Boolean")
                                    || fsimpleName.equals("Integer")
                                    || fsimpleName.equals("Double")
                                    || fsimpleName.equals("Float")
                                    || fsimpleName.equals("Long")) {

                                buffer.append("\"" + field.getName() + "\":"
                                        + field.get(object) + ",");
                            } else if (fsimpleName.equals("Date")) {

                                Date date = (Date) object;
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                                        "yyyy-MM-dd hh:mm:ss");
                                String simdate = simpleDateFormat.format(date);
                                buffer.append("\"" + field.getName() + "\":"
                                        + simdate + ",");
                            } else {

                                buffer = beanTojson(fieldobj, buffer).append(
                                        ",");
                            }
                        }

                    }

                    buffer = new StringBuffer(""
                            + buffer.substring(0, buffer.length() - 1) + "");
                    buffer.append("},");
                }
            }

        }

        buffer = new StringBuffer("" + buffer.substring(0, buffer.length() - 1)
                + "");
        buffer.append("]");

        return buffer;
    }

    public static StringBuffer beanTojson(Object obj, StringBuffer buffer)
            throws IllegalArgumentException, IllegalAccessException {

        Class clazz = obj.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        Field.setAccessible(declaredFields, true);

        buffer.append("\"" + clazz.getSimpleName() + "\":{");

        for (Field field : declaredFields) {

            Object object = field.get(obj);
            String fieldName = field.getType().getSimpleName();

            if (object == null) {
                if (fieldName.equals("String")) {
                    buffer.append("\"" + field.getName() + "\":\"\",");
                }

                else {
                    buffer.append("\"" + field.getName() + "\":null,");
                }

            } else {

                Class fieldclass = object.getClass();
                String simpleName = fieldclass.getSimpleName();

                if (simpleName.equals("String")) {

                    buffer.append("\"" + field.getName() + "\":\""
                            + field.get(obj) + "\",");
                } else if (simpleName.equals("Boolean")
                        || simpleName.equals("Integer")
                        || simpleName.equals("Double")
                        || simpleName.equals("Float")
                        || simpleName.equals("Long")) {

                    buffer.append("\"" + field.getName() + "\":"
                            + field.get(obj) + ",");
                } else if (simpleName.equals("Date")) {

                    Date date = (Date) object;
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                            "yyyy-MM-dd hh:mm:ss");
                    String simdate = simpleDateFormat.format(date);
                    buffer.append("\"" + field.getName() + "\":\"" + simdate
                            + "\",");
                } else if (simpleName.equals("ArrayList")
                        || simpleName.equals("LinkedList")) {

                    List list = (List) object;
                    buffer = listTojson(buffer, list);
                } else {
                    buffer = beanTojson(object, buffer).append("}");
                }
            }

        }

        buffer = new StringBuffer("" + buffer.substring(0, buffer.length() - 1)
                + "");
        buffer.append("}");

        return buffer;
    }

}
 
 

使用方法

1.先定义好自己的返回样式

public class Result {
  int code;
  String message;
  List pigArray;
  public int getCode() {
      return code;
  }
  public void setCode(int code) {
      this.code = code;
  }
  public String getMessage() {
      return message;
  }
  public void setMessage(String message) {
      this.message = message;
  }
  public List getPigArray() {
      return pigArray;
  }
  public void setPigArray(List pigArray) {
      this.pigArray = pigArray;
  }

  

}

public class Pig {
   int age;
   int weight;
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
public int getWeight() {
    return weight;
}
public void setWeight(int weight) {
    this.weight = weight;
}
   
}

最后在程序中调用

           Result rs=new Result();
        rs.setCode(1);
        rs.setMessage("用户有数据");
        List list=new ArrayList();
        Pig p= new Pig();
        p.setAge(10);
        p.setWeight(23);
        list.add(p);
        rs.setPigArray(list);
        System.out.println("json:" +JsonUtil.class2json(rs));

效果如下:

{
    "code": 1,
    "message": "用户有数据",
    "pigArray": [{
        "age": 10,
        "weight": 23
    }]
}

你可能感兴趣的:(使用java反射简单模拟json数据)