You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

106 lines
3.5 KiB

package com.zdxt.common.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
/**
* Fastjson2 解析工具。
* <p>
* 兼容包对 String 走 JSONReaderUTF16,在部分 JDK(尤其 Oracle/麒麟 aarch64)上会误报
* {@code invalid escape character EOI}。统一走 UTF-8 字节解析规避该问题,失败时再用 Jackson 兜底。
*/
public final class FastJsonUtil {
private static final ObjectMapper JACKSON = new ObjectMapper();
private FastJsonUtil() {
}
public static JSONObject parseObject(String text) {
if (text == null) {
return null;
}
String trimmed = text.trim();
if (trimmed.isEmpty() || "null".equalsIgnoreCase(trimmed)) {
return null;
}
try {
// 关键 UTF-8 字节路径,避开 JSONReaderUTF16 的 EOI 误判
return JSON.parseObject(trimmed.getBytes(StandardCharsets.UTF_8));
} catch (Exception fastjsonEx) {
try {
@SuppressWarnings("unchecked")
Map<String, Object> map = JACKSON.readValue(trimmed, Map.class);
return new JSONObject(map);
} catch (Exception jacksonEx) {
fastjsonEx.addSuppressed(jacksonEx);
if (fastjsonEx instanceof RuntimeException) {
throw (RuntimeException) fastjsonEx;
}
throw new RuntimeException(fastjsonEx);
}
}
}
public static JSONArray parseArray(String text) {
if (text == null) {
return null;
}
String trimmed = text.trim();
if (trimmed.isEmpty() || "null".equalsIgnoreCase(trimmed)) {
return null;
}
try {
Object parsed = JSON.parse(trimmed.getBytes(StandardCharsets.UTF_8));
if (parsed instanceof JSONArray) {
return (JSONArray) parsed;
}
if (parsed == null) {
return null;
}
JSONArray arr = new JSONArray();
arr.add(parsed);
return arr;
} catch (Exception fastjsonEx) {
try {
List<?> list = JACKSON.readValue(trimmed, List.class);
return new JSONArray(list);
} catch (Exception jacksonEx) {
fastjsonEx.addSuppressed(jacksonEx);
if (fastjsonEx instanceof RuntimeException) {
throw (RuntimeException) fastjsonEx;
}
throw new RuntimeException(fastjsonEx);
}
}
}
public static <T> T parseObject(String text, Class<T> clazz) {
if (text == null) {
return null;
}
String trimmed = text.trim();
if (trimmed.isEmpty() || "null".equalsIgnoreCase(trimmed)) {
return null;
}
try {
return JSON.parseObject(trimmed.getBytes(StandardCharsets.UTF_8), clazz);
} catch (Exception fastjsonEx) {
try {
return JACKSON.readValue(trimmed, clazz);
} catch (Exception jacksonEx) {
fastjsonEx.addSuppressed(jacksonEx);
if (fastjsonEx instanceof RuntimeException) {
throw (RuntimeException) fastjsonEx;
}
throw new RuntimeException(fastjsonEx);
}
}
}
}