Java中如何获取JSON对象的嵌套元素?已实现一级键读取
解决Jackson读取JSON二级节点值的问题
问题描述
我有如下JSON文件test.json:
{ "type" : "object", "id" : "123", "title" : "Test", "properties" : { "_picnic" : { "type" : "boolean" } } }
我可以通过以下代码获取JSON一级键的值,比如获取type键得到object:
public static void main(String[] args){ String exampleRequest = null; ObjectMapper objectMapper = new ObjectMapper(); try { exampleRequest = FileUtils.readFileToString(new File("src/main/resources/test.json"), StandardCharsets.UTF_8); JsonNode jsonNode = objectMapper.readTree(exampleRequest); String type = jsonNode.get("type").asText(); System.out.println(type); } catch (IOException e) { throw new RuntimeException(e); } }
但尝试获取二级元素的值时没有响应,比如执行以下代码都无法得到预期结果:
// 直接获取_picnic失败 String type = jsonNode.get("_picnic").asText(); System.out.println(type); // 获取properties对象失败 String type = jsonNode.get("properties").asText(); System.out.println(type);
我试过用properties._picnic或properties[0]_picnic的写法,也都没效果。
解决方案
1. 获取二级节点_picnic的type值
_picnic是properties节点下的子对象,不能直接从根节点获取,需要逐层遍历:
public static void main(String[] args){ String exampleRequest = null; ObjectMapper objectMapper = new ObjectMapper(); try { exampleRequest = FileUtils.readFileToString(new File("src/main/resources/test.json"), StandardCharsets.UTF_8); JsonNode jsonNode = objectMapper.readTree(exampleRequest); // 先获取properties节点 JsonNode propertiesNode = jsonNode.get("properties"); // 再从properties节点获取_picnic节点 JsonNode picnicNode = propertiesNode.get("_picnic"); // 最后读取_picnic下的type值 String picnicType = picnicNode.get("type").asText(); System.out.println(picnicType); // 输出:boolean } catch (IOException e) { throw new RuntimeException(e); } }
2. 正确获取整个properties对象
properties是JSON对象类型,不能用asText()方法读取(该方法仅适用于字符串类型节点),可以用以下方式输出:
// 获取properties节点 JsonNode propertiesNode = jsonNode.get("properties"); // 直接输出JSON格式字符串 System.out.println(propertiesNode.toString()); // 输出结果:{"_picnic":{"type":"boolean"}} // 或者用Jackson方法格式化输出 String propertiesStr = objectMapper.writeValueAsString(propertiesNode); System.out.println(propertiesStr);
关键注意点
JsonNode.get(String)只能读取当前节点的直接子节点,不支持.分隔的路径语法,必须逐层获取子节点。asText()仅适用于字符串类型节点,对象或数组类型节点调用该方法会返回空字符串,需保留JsonNode类型进行后续操作。
内容的提问来源于stack exchange,提问作者drmaa
相关产品推荐
相关产品推荐

