对象转换成集合
因为在业务开发过程中需要使用到
对象转换为JSON
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
代码案例
/**
* 对象转Map工具类
*/
public String BeanToMap(T beau,String url) throws IllegalAccessException {
Class<?> aClass = beau.getClass();
Field[] fields = aClass.getDeclaredFields();
Map<String, Object> JSONMap = new HashMap<>();
for (Field field : fields) {
//强制获取
field.setAccessible(true);
if (!ObjectUtils.isEmpty(field.get(beau))) {
JSONMap.put(field.getName(), field.get(beau));
}
}
JSONMap.put("url",url);
//增强 转换为JSON字符串
String json = JSON.toJSONString(JSONMap);
return json;
}
实体类
@Data
public class Student {
private String name;
private Integer age;
private Double hight;
}
测试类
@Test
public void sss() {
Student stu = new Student();
stu.setName("张三");
stu.setAge(11);
stu.setHight(56.6);
String url = "baidu.com";
try {
String json = dataValidationUtils.BeanToMap(stu, url);
System.out.println(json);
} catch (IllegalAccessException e) {
log.error(e.getMessage());
}
}
对象转换map
/**
* 对象转JSON工具类
*/
public Map<String, Object> BeanToJSON(T beau) throws IllegalAccessException {
Class<?> aClass = beau.getClass();
Field[] fields = aClass.getDeclaredFields();
Map<String, Object> JSONMap = new HashMap<>();
for (Field field : fields) {
//强制获取
field.setAccessible(true);
if (!ObjectUtils.isEmpty(field.get(beau))) {
JSONMap.put(field.getName(), field.get(beau));
}
}
return JSONMap;
}
THE END
暂无评论内容