zoukankan      html  css  js  c++  java
  • 『类型转换』Object转Map、Map转Object

    fastjson

    User user = new User();
    user.setName("Java");
    user.setAge(26);

    //Object转Map Map map = JSONObject.parseObject(JSONObject.toJSONString(user), Map.class);
    Map<String,Object> map = JSONObject.parseObject(JSON.toJSONString(user));
    //Map转Object User user = JSON.parseObject(JSON.toJSONString(map), User.class); User user = JSONObject.toJavaObject(JSON.toJSONString(map), User.class);

    jackson

    String转Map<String,Map<String,Double>>
    String test;
    Map<String,Map<String,Double>> map = new HashMap<>();
    ObjectMapper mapper = new ObjectMapper();
    try{
      map = mapper.readValue(tset,new TypeReference<Map<String,Map<String,Double>>>(){});
    }catch(Exception e){
        e.printStackTrace();
    }


    //对象转map
    Map m = mapper.readValue(mapper.writeValueAsString(user), Map.class);

    //map转对象
    User user = mapper.readValue(mapper.writeValueAsString(m), User.class);

    还可以用org.apache.commons.beanutils.BeanMap进行转换

    Map<String, Object> map = new org.apache.commons.beanutils.BeanMap(user);

    还可以用org.apache.commons.beanutils.BeanUtils将map转为对象

    BeanUtils.populate(user, map);
  • 相关阅读:
    CentOS 6.x 系统安装选项说明
    MySQL表的操作
    6月13号
    6月11号
    6月10号
    6月9号
    6月6
    day27
    day 28
    day 29
  • 原文地址:https://www.cnblogs.com/yan-sh/p/13718671.html
Copyright © 2011-2022 走看看