包含Map的对象json序列化与反序列化,map对象json序列化,通过json-lib包含
分享于 点击 33231 次 点评:196
包含Map的对象json序列化与反序列化,map对象json序列化,通过json-lib包含
通过json-lib包含Map的对象的json序列化与反序列化。
[Java]代码
//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; }
用户点评