org.swiftboot.util.JsonUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of swiftboot-utils Show documentation
Show all versions of swiftboot-utils Show documentation
Utils library for enterprise applications
The newest version!
package org.swiftboot.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Map;
/**
* 依赖 Jackson 库
*
* @author swiftech
*/
public class JsonUtils {
static Logger log = LoggerFactory.getLogger(JsonUtils.class);
/**
* 按照格式 "xxx.xxx.xxx" 递归选中 JSON 树中的子节点
*
* @param rootNode
* @param selector
* @return
*/
public static Object select(JsonNode rootNode, String selector) {
String[] keys = StringUtils.split(selector, '.');
log.debug("Select in " + rootNode.toString());
try {
JsonNode found = _select(rootNode, keys, 0);
return found.textValue().trim();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static JsonNode _select(JsonNode curNode, String[] keys, int idx) {
if (idx >= keys.length) {
return curNode;// Already last one, just return null.
}
log.debug(" select " + keys[idx]);
curNode = curNode.path(keys[idx++]);
if (curNode.isNull() || curNode.isMissingNode()) {
throw new RuntimeException(Info.get(JsonUtils.class, R.NO_DATA_FOUND1, ArrayUtils.toString(keys)));
}
return _select(curNode, keys, idx);
}
/**
* JSON 格式字符串转换为 Map
*
* @param strJson
* @return
* @throws IOException
*/
public static Map jsonToMap(String strJson) throws IOException {
ObjectMapper mapper = getJava8ObjectMapper();
return mapper.readValue(strJson, new TypeReference