Map转换为bean

Map转Bean实践
本文介绍了一种将Map数据结构转换为Java Bean的方法,特别适用于Map中包含List的情况。通过使用commons-beanutils库,实现了从Map到特定Java Bean类的转换,并支持日期格式化和子对象的递归转换。

Map转换为bean,Map里可以包含List,需要的包commons-beanutils.jar

1 转换类(DefaultResult)

public void fromMap(Map<String, Object> map,String datePattern,Map<String, Class> type) {
        BeanMap beanMap = new BeanMap(this);
        for(Object obj : beanMap.keySet()){
            if(map.containsKey(obj.toString())){
                Object value = map.get(obj.toString());
                if(value instanceof Date){
                    beanMap.put(obj, DateFormatUtils.format((Date)value, datePattern));
                }if(value instanceof List){
                    List toList = new ArrayList();
                    List list= (List)value;
                    for(Object subObj : list){
                        try {
                            Object temp = (type.get(obj.toString()).newInstance());
                            DefaultResult result = (DefaultResult)temp;
                            result.fromBean(subObj);
                            toList.add(result);
                        } catch (InstantiationException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                        
                    }
                    beanMap.put(obj, toList);
                }else{
                    
                    beanMap.put(obj, value);
                }
            }
        }
    }



    public void fromMap(Map<String, Object> map){
        fromMap(map,defaultDateFromatPattern);
        
    }
    
    public void fromMap(Map<String, Object> map,String datePattern){
        fromMap(map, datePattern, null);
    }
    
    
    public void fromBean(Object obj){
        try {
            BeanUtils.copyProperties(this, obj);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

2 需要转换的VO

public class GameWholelistResult extends DefaultResult{
    private boolean hasnext;
    private Integer total;
    
    private List<GameListResult> list;
    
    private List<BannerListResult> blist;
    
    public boolean isHasnext() {
        return hasnext;
    }

    public void setHasnext(boolean hasnext) {
        this.hasnext = hasnext;
    }

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }

    public List<GameListResult> getList() {
        return list;
    }

    public void setList(List<GameListResult> list) {
        this.list = list;
    }

    public List<BannerListResult> getBlist() {
        return blist;
    }

    public void setBlist(List<BannerListResult> blist) {
        this.blist = blist;
    }
    
    public static class GameListResult extends DefaultResult{
        
        private String id;
        private String name;
        private String logo;
        private String createtime;
        private String typeid;
        private String typename;
        private Integer appsize;
        private Integer apprank;
        private String ages;
        private String childtype;
        private Integer downloadcount;
        private Integer commentcount;
        private String version;
        private String pkg;
        
        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getLogo() {
            return logo;
        }

        public void setLogo(String logo) {
            this.logo = logo;
        }

        public String getCreatetime() {
            return createtime;
        }

        public void setCreatetime(String createtime) {
            this.createtime = createtime;
        }

        public String getTypeid() {
            return typeid;
        }

        public void setTypeid(String typeid) {
            this.typeid = typeid;
        }

        public String getTypename() {
            return typename;
        }

        public void setTypename(String typename) {
            this.typename = typename;
        }

        public Integer getAppsize() {
            return appsize;
        }

        public void setAppsize(Integer appsize) {
            this.appsize = appsize;
        }

        public Integer getApprank() {
            return apprank;
        }

        public void setApprank(Integer apprank) {
            this.apprank = apprank;
        }

        public String getAges() {
            return ages;
        }

        public void setAges(String ages) {
            this.ages = ages;
        }

        public String getChildtype() {
            return childtype;
        }

        public void setChildtype(String childtype) {
            this.childtype = childtype;
        }

        public Integer getDownloadcount() {
            return downloadcount;
        }

        public void setDownloadcount(Integer downloadcount) {
            this.downloadcount = downloadcount;
        }

        public Integer getCommentcount() {
            return commentcount;
        }

        public void setCommentcount(Integer commentcount) {
            this.commentcount = commentcount;
        }

        public String getVersion() {
            return version;
        }

        public void setVersion(String version) {
            this.version = version;
        }

        public String getPkg() {
            return pkg;
        }

        public void setPkg(String pkg) {
            this.pkg = pkg;
        }
        
        @Override
        @JsonIgnore
        public Integer getStatus() {
            return super.getStatus();
        }
        
        @Override
        @JsonIgnore
        public String getErrormessage() {
            return super.getErrormessage();
        }
    }
    
    public static class BannerListResult extends DefaultResult{
        
        
        private String image;
        private Integer locationtype;
        private String locationid;


        public String getImage() {
            return image;
        }

        public void setImage(String image) {
            this.image = image;
        }

        public Integer getLocationtype() {
            return locationtype;
        }

        public void setLocationtype(Integer locationtype) {
            this.locationtype = locationtype;
        }

        public String getLocationid() {
            return locationid;
        }

        public void setLocationid(String locationid) {
            this.locationid = locationid;
        }
        
        public boolean ignoreDefault(){
            return true;
        }
        
        @Override
        @JsonIgnore
        public Integer getStatus() {
            return super.getStatus();
        }
        
        @Override
        @JsonIgnore
        public String getErrormessage() {
            return super.getErrormessage();
        }
    }
    
    /*public GameListResult getNewGameListResult(){
        return new GameListResult();
    }
    
    public BannerListResult getNewBannerListResult(){
        return new BannerListResult();
    }*/
    

}

3  实现用法

Map<String , Class> classType= new HashMap<String, Class>();
classType.put("blist", BannerListResult.class); classType.put("list", GameListResult.class); GameWholelistResult gameWholelistResult = new GameWholelistResult(); ameWholelistResult.fromMap(resultMap,"yyyy-MM-dd",classType);

具体的实现,大家可以看看源码,能够更清晰原理

 

转载于:https://www.cnblogs.com/qiyingjing/archive/2013/04/16/3023457.html

### 将Map转换为临时Bean的Java实现方法 在实际开发中,有时需要将 `Map` 转换为 Java Bean 对象。可以通过多种方式来完成这一操作,以下是几种常见的解决方案。 #### 方法一:使用 Apache Commons BeanUtils 的 PropertyUtils Apache Commons BeanUtils 提供了一个工具类 `PropertyUtils`,可以用来设置对象的属性值。下面是一个简单的示例: ```java import org.apache.commons.beanutils.PropertyUtils; import java.lang.reflect.InvocationTargetException; import java.util.Map; public class MapToBeanConverter { public static <T> T convert(Map<String, Object> map, Class<T> beanClass) throws IllegalAccessException, InstantiationException, InvocationTargetException { T obj = beanClass.getDeclaredConstructor().newInstance(); for (Map.Entry<String, Object> entry : map.entrySet()) { String propertyName = entry.getKey(); Object propertyValue = entry.getValue(); PropertyUtils.setProperty(obj, propertyName, propertyValue); } return obj; } } ``` 上述代码展示了如何利用 `PropertyUtils.setProperty()` 来动态地为对象赋值[^1]。 --- #### 方法二:使用 Jackson 库进行反序列化 Jackson 是一个强大的 JSON 处理库,也可以轻松地将 `Map` 转换为 Java Bean 对象。下面是具体实现: ```java import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Map; public class MapToBeanWithJackson { public static <T> T convert(Map<String, Object> map, Class<T> beanClass) throws Exception { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.convertValue(map, beanClass); } } ``` 此方法简单高效,适合处理复杂的嵌套结构数据[^4]。 --- #### 方法三:使用 MapStruct 进行映射 虽然 MapStruct 主要用于 Java Bean 之间的相互转换,但它也支持从 `Map` 到 Java Bean 的映射。首先需要定义一个 Mapper 接口,并指定映射逻辑: ```java import org.mapstruct.Mapper; import org.mapstruct.MappingTarget; import org.mapstruct.factory.Mappers; import java.util.Map; @Mapper public interface MyMapper { MyMapper INSTANCE = Mappers.getMapper(MyMapper.class); void fromMapToBean(Map<String, ?> map, @MappingTarget TargetBean target); default TargetBean fromMap(Map<String, ?> map) { TargetBean target = new TargetBean(); fromMapToBean(map, target); return target; } } class TargetBean { private String name; private int age; // Getters and Setters } ``` 调用时可以直接使用 `MyMapper.INSTANCE.fromMap()` 完成转换[^2][^3]。 --- ### 总结 以上三种方法各有优劣: - **Apache Commons BeanUtils**:功能强大,但可能因反射带来一定的性能开销。 - **Jackson**:易于使用,尤其适合复杂的数据结构。 - **MapStruct**:类型安全且性能高,但在某些场景下需要额外配置。 根据项目需求和技术栈选择合适的方案即可。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值