Java通過key直接擷取json字串的value,json無需轉換
阿新 • • 發佈:2019-02-14
例如想擷取scoreClass
這是json資料
擷取程式碼"extra_info": { "fm_info": { "riskService": { "reason_code": "001:使用者認證", "success": false } }, "application_attribute": { "company_industry": "unknown", "estimate_salary": 10000, "social_last_handin_base": -1, "loan_platform_cnt": 0, "loan_cnt": 0, "applied_amount_sum": 0, "alipay_auth": false, "social_auth": false, "credit_card_auth": false, "staff_level": "B", "scoreClass": "D", "increaseAmount": false, "approval_tips": [ ] } }
String scoreClass = JacksonUtils.getInstance().fetchValue(responseData, "payload:extra_info:application_attribute:scoreClass2");
工具類
public class JacksonUtils { private static final Logger LOGGER = LoggerFactory.getLogger(JacksonUtils.class); private static final ObjectMapper MAPPER = new ObjectMapper(); private static final JacksonUtils CONVERSION = new JacksonUtils(); private static final String SEPARATOR = ":"; private JacksonUtils() { init(); } private static void init() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); MAPPER.setDateFormat(dateFormat); MAPPER.setSerializationInclusion(Include.NON_NULL); } public static JacksonUtils getInstance() { return CONVERSION; } public String pojo2Json(Object obj) throws IOException { StringWriter writer = new StringWriter(); MAPPER.writeValue(writer, obj); return writer.toString(); } public <T> T json2Pojo(InputStream jsonStream, Class<T> classType) throws IOException { T t = null; try (InputStream inputStream = jsonStream) { t = MAPPER.readValue(inputStream, classType); } return t; } public <T> T json2Pojo(String json, Class<T> classType) { try { return MAPPER.readValue(json, classType); } catch (Exception e) { LOGGER.error("Unexpected exception occurred!", e); return null; } } /** * 將JSON轉化為List * * @param json 字串 * @param collectionClass 泛型的Collection * @param elementClasses 元素類 * @return List 轉換後的物件 */ public static List<?> jsonConverList(String json, Class<?>... elementClasses) { try { return MAPPER.readValue(json, getCollectionType(List.class, elementClasses)); } catch (Exception e) { LOGGER.error("Unexpected exception occurred!", e); return null; } } /** * 獲取泛型的Collection Type * * @param collectionClass 泛型的Collection * @param elementClasses 元素類 * @return JavaType Java型別 */ public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) { return MAPPER.getTypeFactory().constructParametricType(collectionClass, elementClasses); } 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) { LOGGER.error("Unexpected exception occurred!", e); return null; } if (tempNode != null) { String value = tempNode.asText(); if (value == null || value.isEmpty()) { value = tempNode.toString(); } return value; } return null; } private JsonNode fetchValueFromObject(JsonNode jsonNode, String fieldName) { return jsonNode.get(fieldName); } private JsonNode fetchValueFromArray(JsonNode jsonNode, String index) { return jsonNode.get(Integer.parseInt(index)); } public JsonNode convertStr2JsonNode(String json) { try { return MAPPER.readTree(json); } catch (Exception e) { LOGGER.error("Unexpected exception occurred!", e); return null; } } }
補充這裡需要引入依賴
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.7.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.7.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.4</version> </dependency>