/*** 功能描述:
* 将json转换成DTO对象** @param jsonStr {}* @return dto* @see [相关类/方法](可选)* @since [产品/模块版本](可选)*/ public staticT json2DTO(String jsonStr, Class tClass) {Gson gson = new Gson();try {return gson.fromJson(jsonStr, tClass);} catch (Exception e) {log.error("【对象转换】错误, json=" + jsonStr, e);throw new RuntimeException(McmpErrorEnum.CONVERTER_ERROR);} }
/*** 功能描述:
* 将Map转换成DTO对象** @param params {}* @return dto* @see [相关类/方法](可选)* @since [产品/模块版本](可选)*/ public staticT map2DTO(Map params, Class tClass) {if (params == null) {return null;}try {String jsonStr = toJson(params);return json2DTO(jsonStr, tClass);} catch (Exception e) {log.error("【对象转换】错误, map=" + params, e);throw new McmpComException(McmpErrorEnum.CONVERTER_ERROR);} }public static String toJson(Object obj) {Gson gson = new Gson();return gson.toJson(obj); }
/*** 功能描述:
* 将List的map对象转换成List的DTO对象** @param listMap list
/**
* json字符串转换成map
* Eliminate JSONObject, JSONArray
*
* @param jsonString
* @author 20020637
* @return HashMap
* */
public static HashMap
if (StringUtils.isEmpty(jsonString)) {
return new HashMap<>();
}
HashMap
if (MapUtils.isEmpty(jsonMap)) {
return new HashMap<>();
}
HashMap
for (Map.Entry
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) value;
List list = handleJSONArray(jsonArray);
resultMap.put(key, list);
} else {
resultMap.put(key, value);
}
}
return resultMap;
}
private static List handleJSONArray(JSONArray jsonArray) {
List list = new ArrayList();
for (Object object : jsonArray) {
if (object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
HashMap map = new HashMap
for (Map.Entry entry : jsonObject.entrySet()) {
Object obj = entry.getValue();
if (obj instanceof JSONArray) {
map.put(entry.getKey(), handleJSONArray((JSONArray) entry.getValue()));
} else if (obj instanceof JSONObject) {
map.put(entry.getKey(), handleJSONObject((JSONObject) entry.getValue()));
} else {
map.put(entry.getKey(), entry.getValue());
}
}
list.add(map);
} else {
list.add(object);
}
}
return list;
}
private static Object handleJSONObject(JSONObject jsonObject){
Map
for (Entry
map.put(_en2.getKey(), _en2.getValue());
}
return map;
}
/**** 功能描述:
* 将dto转换为map* 推荐,此方法优于 DalUtils.convertToMap 方法* @param dto {}* @return map* @see DalUtils#convertToMap(Object)* @since [产品/模块版本](可选)*/ public static HashMapconvertDTOToMap(Object dto) {if (dto == null) {return new HashMap<>();}// 支持值为null的属性转换Gson gson = new GsonBuilder().serializeNulls().create();String json = gson.toJson(dto);return json2HashMap(json); }
/**** 功能描述:
* 将list转换为list