这里创建一个User对象 :User user = new User();
用到了fastjson,引入了fastjson的依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency>
Map、实体类转Json
// 将 Map 转换为 Json
String s = JSON.toJSONString(user01)
System.out.println(s);
// 将 User 转换为 Json
String s2 = JSON.toJSONString(User)
System.out.println(s2);
Json转Map、对象
// 将 Json 转换为 Map
Map map = JSON.parseObject(s, Map.class);
System.out.println(map);
// 将 Json 转换为 实体类
User user = JSON.parseObject(s2, User.class);
System.out.println(user);
Map与对象
第一种方式:至于实体类和Map之间的转换,先转成json就行了
第二种方式:
// Map转对象
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);
map.put(fieldName, value);
}
return map;
}