JSON对象转JAVA实体对象

2022-07-15 09:09:25

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()));}
  • 作者:wushifeng_
  • 原文链接:https://blog.csdn.net/wushifeng_/article/details/121809741
    更新时间:2022-07-15 09:09:25