json 도구 변환
2751 단어 테크니컬
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;
}
기성 가방이나 더 좋은 방법이 있는지 모르겠지만 문서를 쓸 때 사용해 시간을 절약하세요.