/** * @author hailou * @Description * @Date on 2020/9/16 15:57 */ public class JacksonUtils {
private static final ObjectMapper MAPPER = new ObjectMapper(); private static final JacksonUtils CONVERSION = new JacksonUtils(); private static final String SEPARATOR = "\\.";
public <T> T map2Pojo(Map<String, Object> map, Class<T> classType) throws IOException { return MAPPER.convertValue(map, classType); }
public <T> T jsonParse(String json) throws IOException { return MAPPER.readValue(json, new TypeReference<T>() {}); }
/** * path: Like xpath, to find the specific value via path. Use :(Colon) to separate different key * name or index. For example: JSON content: { "name": "One Guy", "details": [ * {"education_first": "xx school"}, {"education_second": "yy school"}, {"education_third": * "zz school"}, ... ] } * * To find the value of "education_second", the path="details:1:education_second". * * @param json * @param path * @return */ public String fetchValue(String json, String path) { JsonNode tempNode = null; try { JsonNode jsonNode = MAPPER.readTree(json); tempNode = jsonNode; String[] paths = path.split(SEPARATOR);
for (String fieldName : paths) { if (tempNode.isArray()) { tempNode = fetchValueFromArray(tempNode, fieldName); } else { tempNode = fetchValueFromObject(tempNode, fieldName); } } } catch (Exception e) { e.printStackTrace(); return null; } if (tempNode != null) { String value = tempNode.asText();
if (value == null || value.isEmpty()) { value = tempNode.toString(); } return value; } return null; }