JSON对象转实体对象@TOC
JSON对象转JAVA实体对象
importcom.alibaba.fastjson.JSONObject;importcn.hutool.core.util.StrUtil;importcn.hutool.core.bean.BeanUtil;/**
* JSON对象转JAVA实体对象 (json对象key值支持下划线分割格式)
* @param jsonObject
* @param t
* @param <T>
*/publicstatic<T>voidJSON2Bean(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>
*/publicstatic<T>voidJSON2Bean(JSONObject jsonObject,T t){Field[] declaredFields= t.getClass().getDeclaredFields();// 获取实体属性,过滤掉json对象中不属于此对象的keySet<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()));}