import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
/**
* JsonUtil
*/
public class JsonUtil {
public static final String JSON_ARRAY_PREFIX = "[";
public static final String JSON_PREFIX = "{";
private static ObjectMapper objectMapper = createObjectMapper();
private JsonUtil() {
}
private static ObjectMapper createObjectMapper(){
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,true);
objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
objectMapper.setTimeZone(TimeZone.getDefault());
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
SimpleModule module = new SimpleModule();
module.addDeserializer(Boolean.class, new BooleanDeserializer());
module.addDeserializer(Date.class, new DateDeserializer());
objectMapper.registerModule(module);
return objectMapper;
}
public static JsonMap parse(String text) {
if (StringUtils.isEmpty(text)) {
return null;
}
return toJsonMap(text, objectMapper);
}
public static <T> T parseObject(String text, TypeReference<T> typeReference) {
if (StringUtils.isEmpty(text)) {
return null;
}
try {
return objectMapper.readValue(text, typeReference);
} catch (IOException e) {
throw new SystemException(Enum.INVALID_REQUEST, e);
}
}
public static <T> T toJavaObject(Map map, Class<T> clazz) {
try {
return objectMapper.convertValue(map, clazz);
} catch (Exception e) {
throw new SystemException(Enum.INVALID_REQUEST, e);
}
}
public static <T> T parseObject(String text, Class<T> clazz) {
if (StringUtils.isEmpty(text)) {
return null;
}
try {
return objectMapper.readValue(text, clazz);
} catch (IOException e) {
throw new SystemException(Enum.INVALID_REQUEST, e);
}
}
private static JsonMap toJsonMap(String text, ObjectMapper objectMapper) {
if (StringUtils.isEmpty(text)) {
return new JsonMap();
}
try {
return objectMapper.readValue(text, JsonMap.class);
} catch (Exception e) {
throw new SystemException(Enum.INVALID_REQUEST, e);
}
}
public static JsonMap toJsonMap(String text) {
ObjectMapper objectMapper = createObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"));
return toJsonMap(text, objectMapper);
}
public static JsonMap toJsonMapWithoutDate(String text) {
return toJsonMap(text, objectMapper);
}
public static JsonMap objToJsonMap(Object obj) {
if (obj == null) {
return new JsonMap();
}
if (obj instanceof Collection) {
throw new IllegalArgumentException("cannot convert a collection to map");
}
return objectMapper.convertValue(obj, JsonMap.class);
}
public static String toJsonStringWithoutFeature(Object object) {
return toJsonString(object, objectMapper);
}
private static String toJsonString(Object object, ObjectMapper objectMapper) {
if (object == null) {
return null;
}
try {
return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new SystemException(Enum.SYSTEM_ERROR, e);
}
}
public static String toJsonString(Object object) {
return toJSONStringWithDateFormat(object, "yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
}
public static String toJSONStringWithDateFormat(Object object, String dateFormat) {
ObjectMapper objectMapper = createObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat(dateFormat));
return toJsonString(object, objectMapper);
}
public static String toJsonArray(List<String> list) {
if (CollectionUtils.isEmpty(list)) {
list = Collections.emptyList();
}
return toJsonString(list);
}
public static List<String> fromJsonArray(String text) {
return parseArray(text, new TypeReference<List<String>>() {});
}
public static <T> List<T> parseArray(String text, TypeReference<List<T>> listType) {
if (StringUtils.isBlank(text) || listType == null) {
return Collections.emptyList();
}
try {
return objectMapper.readValue(text, listType);
} catch (Exception e) {
throw new SystemException(Enum.INVALID_REQUEST, e);
}
}
public static List<Object> parseArray(String text) {
return parseArray(text, new TypeReference<List<Object>>() {});
}
public static Object parseTxt2Json(String txt) {
Object result = txt;
if (txt != null) {
try {
if (txt.startsWith(JSON_ARRAY_PREFIX)) {
result = parseArray(txt);
} else if (txt.startsWith(JSON_PREFIX)) {
result = toJsonMap(txt);
}
} catch (Exception e) {
throw new SystemException(Enum.INVALID_REQUEST, e);
}
}
return result;
}
/**
* jobExecution convert into jsonString
*/
public static String toJsonWithLimitLength(Object object, int maxLength) {
String jsonString = toJsonString(object);
if (StringUtils.isBlank(jsonString)) {
return "{}";
}
if (jsonString.length() > maxLength) {
return jsonString.substring(0, maxLength - 1);
}
return jsonString;
}
@SuppressWarnings("squid:S3776")
public static void deepVisit(Map jsonMap, String path, JsonNodeVisitor nodeVisitor) {
if (jsonMap != null) {
List<String> matchedKeys = nodeVisitor.matchedKeys(jsonMap, path);
matchedKeys.forEach(matchedKey -> {
Object val = jsonMap.get(matchedKey);
if (val != null) {
if (!(val instanceof String)) {
val = JsonUtil.toJsonString(val);
}
String fullPath = path + "." + matchedKey;
nodeVisitor.apply(jsonMap, matchedKey, fullPath, val);
}
});
List<String> nextKeys = nodeVisitor.nextKeys(jsonMap, path);
nextKeys.forEach(nextKey -> {
Object val = jsonMap.get(nextKey);
if (val != null) {
String nextPath = path + "." + nextKey;
if (val instanceof Map) {
deepVisit((Map) val, nextPath, nodeVisitor);
} else if (val instanceof List) {
List vals = (List) val;
for (int i = 0; i < vals.size(); i++) {
Object item = vals.get(i);
String idx = "[" + i + "]";
if (item instanceof Map) {
deepVisit((Map) item, nextPath + idx, nodeVisitor);
} else {
nodeVisitor.apply(jsonMap, nextKey, nextPath + idx, item);
}
}
} else if (val instanceof String) {
String strVal = (String) val;
String resultVal = deepVisitStrNode(jsonMap, nextKey, nextPath, nodeVisitor, strVal);
jsonMap.put(nextKey, resultVal);
}
}
});
}
}
private static String deepVisitStrNode(Map jsonMap, String nextKey, String nextPath,
JsonNodeVisitor nodeVisitor, String strVal) {
try {
if (strVal.startsWith(JSON_PREFIX)) {
JsonMap jsonVal = JsonUtil.parse(strVal);
deepVisit(jsonVal, nextPath, nodeVisitor);
return JsonUtil.toJsonString(jsonVal);
} else if (strVal.startsWith(JSON_ARRAY_PREFIX)) {
List<Object> jsonArrayVal = JsonUtil.parseArray(strVal);
for (int i = 0; i < jsonArrayVal.size(); i++) {
Object item = jsonArrayVal.get(i);
String idx = "[" + i + "]";
if (item instanceof Map) {
deepVisit((Map) item, nextPath + idx, nodeVisitor);
} else {
nodeVisitor.apply(jsonMap, nextKey, nextPath + idx, item);
}
}
}
} catch (SystemException e) {
//can not parse string, just ignore
}
return strVal;
}
}
import java.util.List;
import java.util.Map;
/**
* JsonNodeVisitor
*/
public interface JsonNodeVisitor {
/**
* find next keys
* @param node
* @param path
* @return
*/
List<String> nextKeys(Map node, String path);
/**
* find matched keys
* @param node
* @param path
* @return
*/
List<String> matchedKeys(Map node, String path);
/**
* apply
* @param parent
* @param key
* @param fullPath
* @param val
*/
void apply(Map parent, String key, String fullPath, Object val);
}
JsonUtil工具类
最新推荐文章于 2024-10-03 08:26:58 发布
1万+

被折叠的 条评论
为什么被折叠?



