JSON对象转实体对象@TOC
JSON对象转JAVA实体对象
import com.alibaba.fastjson.JSONObject;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.bean.BeanUtil;
/**
* JSON对象转JAVA实体对象 (json对象key值支持下划线分割格式)
* @param jsonObject
* @param t
* @param <T>
*/
public static <T> void JSON2Bean(JSONObject jsonObject, T t) {
jsonObject.entrySet().stream()
.forEach(item -> BeanUtil.setProperty(t, StrUtil.toCamelCase(item.getKey()), item.getValue()));
}
升级版: 过滤掉json对象中不属于此对象的key
/**
* JSON对象转JAVA实体对象 (json对象key值支持下划线分割格式)
* @param jsonObject
* @param t
* @param <T>
*/
public static <T> void JSON2Bean(JSONObject jsonObject, T t) {
Field[] declaredFields = t.getClass().getDeclaredFields();
// 获取实体属性,过滤掉json对象中不属于此对象的key
Set<String> collect = Arrays.asList(declaredFields).stream().map(it -> it.getName()).collect(Collectors.toSet());
jsonObject.entrySet().stream()
.filter(item -> collect.contains(StrUtil.toCamelCase(item.getKey())))
.forEach(item -> BeanUtil.setProperty(t, StrUtil.toCamelCase(item.getKey()), item.getValue()));
}