包含Map的对象json序列化与反序列化

RequestParam 包含一个reqParam的 HashMap<String,Object>对象

 

public static final String MAP_PARAM = "reqParam";
    public static final String MAP_PARAM_CLASS= "reqParam_class";//Map中类名后缀

/**
     * 序列化成Json字符串
     * @param request
     * @return
     * @throws Exception
     */
    public static String toJson(RequestParam request) throws Exception {
        JSONObject jsonOjb = JSONObject.fromObject(request);
        Map<String, Object> map = request.getReqParam();
      
        //Param中无数据
        if(map.isEmpty()){
            return jsonOjb.toString();
        }

        JSONObject mapObj = new JSONObject();
        for(String key:map.keySet()){
            mapObj.put(key, map.get(key).getClass().getName());
        }
        jsonOjb.put(MAP_PARAM_CLASS, mapObj);
        return jsonOjb.toString();
    }
   
    /**
     * Json反序列化
     * @param json
     * @return
     * @throws Exception
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static RequestParam fromJson(String json) throws Exception{
        JSONObject jsonObj=JSONObject.fromObject(json);
        JSONObject jsonMapClass = jsonObj.getJSONObject(MAP_PARAM_CLASS);
        jsonObj.remove(MAP_PARAM_CLASS);
        JSONObject jsonMap = jsonObj.getJSONObject(MAP_PARAM);
        RequestParam request =  (RequestParam) JSONObject.toBean(jsonObj,RequestParam.class);
        //Param中无数据
        if(jsonMapClass==null||jsonMapClass.isNullObject()){
            return request;
        }
        JsonConfig jsonCfg = new JsonConfig();
        jsonCfg.setRootClass(Map.class);
        Map<String,Class> classMap = new HashMap<String, Class>();
        Iterator<String> it = jsonMapClass.keys();
        while(it.hasNext()){
            String key = it.next();
            Class<?> c = Class.forName(jsonMapClass.getString(key));
            classMap.put(key, c);
        }
        jsonCfg.setClassMap(classMap);
        Map<String,Object> map = (Map<String, Object>) JSONObject.toBean(jsonMap, jsonCfg);
        request.getReqParam().putAll(map);
        return request;
    }

转载于:https://my.oschina.net/wy08/blog/42709

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值