場景:目前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);
}
}