『類型轉換』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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。