场景:目前fastJson其实也是经常报漏洞,动不动要升级,确实是一个让人头疼的事情,所以,现在打算弃用fastJosn。自己写了个基础的常用的Java代码来专门做这个处理,后续会完善补充:
@Slf4j
public class JsonUtils {
private static Gson gson = new Gson();
private static final org.codehaus.jackson.map.ObjectMapper MAPPER = new org.codehaus.jackson.map.ObjectMapper();
static {
MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
MAPPER.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
MAPPER.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
/**
* 将String转化为List
*
* @param string
* @return
*/
public static List stringToList(String string) {
if (StringUtils.isBlank(string)) {
return new ArrayList();
}
return gson.fromJson(string, new TypeToken<List>() {
}.getType());
}
/**
* 将对象转换为JSON格式
*
* @param model
* @return
* @throws IOException
*/
public static String toStr(Object model) {
if(Objects.isNull(model)){
return null;
}
try {
return MAPPER.writeValueAsString(model);
} catch (IOException e) {
log.error("JSON: toStr error : {}", model, e);
}
return null;
}
/**
* 将JSON字符串转换为指定类实例
*
* @param <T>
* @param content
* @param clazz
* @return
* @throws IOException
*/
public static <T> T fromStr(String content, Class<T> clazz) {
if(StringUtils.isBlank(content)){
return null;
}
try {
return MAPPER.readValue(content, clazz);
} catch (IOException e) {
log.error("JSON: fromStr error {}", content, e);
}
return null;
}
/**
* 将JSON字符串转换为Map
*
* @param content
* @return
* @throws IOException
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> fromStrToMap(String content) {
return fromStr(content, Map.class);
}
}