包含Map的對象json序列化與反序列化

RequestParam 包含一個reqParam的 HashMap<String,Object>對象json

 

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();
        }rem

        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;
    }字符串

相關文章
相關標籤/搜索