日期:2014-05-20  浏览次数:20768 次

json转map方法
Map<String,CityPo> map = new HashMap<String,CityPo>();
CityPo po = new CityPo();
po.setBuildCfgID(123);
po.setCurHp(456);
Hero hero = new Hero();
hero.setStrAge("11");
hero.setStrName("strName");
po.setHero(hero);
  map.put( "name",po);  
 JSONObject json = JSONObject.fromObject( map ); //将map转成json
 Map tmp = (Map)JSONObject.toBean(json, Map.class); //将json转回map
 但是转回的map是Map<String,Object>的,有没有办法转成Map<String, CityPo>

ps: Map tmp = (Map)JSONObject.toBean(json, Map.class); 其中的Map.class为什么不让设Map<String,CityPo>.class?

------解决方案--------------------
Java code
CityPo po = new CityPo();
    po.setBuildCfgID(123);
    po.setCurHp(456);
    Hero hero = new Hero();
    hero.setStrAge("11");
    hero.setStrName("strName");
    po.setHero(hero);
    map.put("name", po);
    JSONObject json = JSONObject.fromObject(po); // 将map转成json
    CityPo poo = (CityPo) JSONObject.toBean(json, CityPo.class);
    System.out.println(poo);

------解决方案--------------------
我这边有个JAR包可以带泛型转
org.codehaus.jackson.map.ObjectMapper
自己从网上下,用法如下:
Java code
ObjectMapper mapper = new ObjectMapper();
Map<String, CityPo> tmp = mapper.readValue(json, new TypeReference<Map<String, CityPo>>() {});

------解决方案--------------------
JAR包名是:
jackson,有两部分,一个是jackson-core-asl,一个是jackson-mapper-asl
------解决方案--------------------
Map tmp = (Map)JSONObject.toBean(json, Map.class); 改成
Map<String,CityPo> tmp = (Map<String,CityPo>)JSONObject.toBean(json, Map.class);

这样可以吗