Person person =new Person();
person.setAdult(true);
person.setName("1");
// 将对象转换成json字符串
String r = JSONUtil.parseObj(person, false).toString();
System.out.println(r);

将对象转换成 map对象
Map<String, Object> stringObjectMap = objectToMap(person);
System.out.println(stringObjectMap);
public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>();
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = field.get(obj) == null ? "":field.get(obj);
map.put(fieldName, value);
}
return map;
}

本文介绍了如何使用Java将Person对象转换为JSON字符串,并演示了如何将其转换为Map对象的过程。重点在于对象到JSON和数据结构之间的转换技巧。
646

被折叠的 条评论
为什么被折叠?



