转换json工具

每次写接口文档的时候,要写json格式的返回结果或者接受参数的时候,都要把对象实例化一个,每个字段都set一遍,然后再转成json,太麻烦了,所以写了一个工具类,直接转换json的,很简单就是用java.lang.reflect包就可以。

private static Object format(Class clazz)
      throws IllegalAccessException, InstantiationException, InvocationTargetException {
    Object instance = clazz.newInstance();
    Field[] declaredFields = clazz.getDeclaredFields();
    for (Field field : declaredFields) {
      String name = field.getName();
      Class type = field.getType();
      String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
      Method method = null;
      try {
        method = clazz.getDeclaredMethod(methodName, type);
      } catch (NoSuchMethodException e) {
        continue;
      }
      if (type.isAssignableFrom(String.class)) {
        method.invoke(instance, name);
      } else if (type.isAssignableFrom(Integer.class)) {
        method.invoke(instance, 1);
      } else if (type.isAssignableFrom(Long.class)) {
        method.invoke(instance, 1L);
      } else if (type.isAssignableFrom(Double.class)) {
        method.invoke(instance, 1.0);
      } else if (type.isAssignableFrom(Float.class)) {
        method.invoke(instance, 1.0f);
      } else if (type.isAssignableFrom(Short.class)) {
        method.invoke(instance, 1);
      } else if (type.isAssignableFrom(Character.class)) {
        method.invoke(instance, '1');
      } else if (type.isAssignableFrom(Boolean.class)) {
        method.invoke(instance, true);
      } else if (type.isAssignableFrom(Date.class)) {
        method.invoke(instance, new Date());
      } else if (type.isAssignableFrom(List.class)) {
        Type genericType = field.getGenericType();
        if (ParameterizedType.class.isAssignableFrom(genericType.getClass())) {
          for (Type t1 : ((ParameterizedType) genericType).getActualTypeArguments()) {
            Object newInstance = ((Class) t1).newInstance();
            newInstance = format(newInstance.getClass());
            List list = Arrays.asList(newInstance);
            method.invoke(instance, list);
          }
        }
      } else {
        Object newInstance = type.newInstance();
        newInstance = format(newInstance.getClass());
        method.invoke(instance, newInstance);
      }
    }
    return instance;
  }

得到对象之后,用自己工程的json包转换成string就可以了。像我自己使用的是Gson:

 private static String beanToJson(Class clazz)
      throws IllegalAccessException, InvocationTargetException, InstantiationException {
    Gson gson = new Gson();
    String json = gson.toJson(format(clazz));
    return json;
  }


不知道有没有现成的包或者更好的方法,只是写文档的时候用一下,节省时间。

你可能感兴趣的:(技术)