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

论坛 期权论坛 脚本     
匿名技术用户   2021-1-4 03:03   18   0

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 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP