Java中如何从含同名键的JSON结构中提取指定路径的字段值
实现方案
首先先修正你提供的示例JSON的语法问题:1. 字符串值未加双引号 2. options字段实际为对象类型,你误写为数组标识[],修正后的合法JSON如下:
{ "today's lunch": { "options": { "choice 1": { "main": "Burger", "side": "Fries" }, "choice 2": { "main": "Spaghetti", "side": "Bread" } } }, "tomorrow's lunch": { "options": { "choice 1": { "main": "Sandwich", "side": "Chips" }, "choice 2": { "main": "Meatloaf", "side": "Bread" } } } }
方案1:使用Jackson内置JsonPointer(推荐)
JsonPointer是RFC6901定义的标准JSON路径表达式,无需自定义递归即可实现任意指定路径的精准取值,完全匹配你的需求。
实现代码
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonPathExtractor { private static final ObjectMapper objectMapper = new ObjectMapper(); public static String getValueByPath(String jsonStr, String jsonPointerPath) throws JsonProcessingException { JsonNode rootNode = objectMapper.readTree(jsonStr); JsonNode targetNode = rootNode.at(jsonPointerPath); // 路径不存在时返回null if (targetNode.isMissingNode()) { return null; } return targetNode.asText(); } public static void main(String[] args) throws JsonProcessingException { // 填入修正后的午餐JSON字符串 String lunchJson = "..."; // 对应路径 today's lunch -> options -> choice 1 -> main 的JsonPointer表达式 String path = "/today's lunch/options/choice 1/main"; String result = getValueByPath(lunchJson, path); // 输出结果为 Burger System.out.println(result); } }
路径规则说明
- 路径以
/开头,每一层key用/分隔 - 如果key中本身包含
/或者~,需要转义:~转义为~0,/转义为~1
方案2:自定义层级匹配实现
如果你不想用JsonPointer,也可以封装逐层匹配的方法,传入按顺序的层级key数组即可精准取值:
public static String getValueByLevelKeys(String jsonStr, String... levelKeys) throws JsonProcessingException { JsonNode currentNode = objectMapper.readTree(jsonStr); for (String key : levelKeys) { if (currentNode == null || currentNode.isMissingNode()) { return null; } currentNode = currentNode.path(key); } return currentNode.isValueNode() ? currentNode.asText() : null; } // 调用示例 String result = getValueByLevelKeys(lunchJson, "today's lunch", "options", "choice 1", "main");
内容的提问来源于stack exchange,提问作者Aaron Zeng
相关产品推荐
相关产品推荐

