简体   繁体   English

从嵌套 JSON 对象中检索键和值的问题

[英]Issue retrieving keys and values from nested JSON object

I need help retrieving the keys and values of this nested JSON .我需要帮助来检索这个嵌套JSON的键和值。 It is a JSON object of multiple values wrapped in another JSON object that is finally wrapped in an array.它是一个包含多个值的JSON对象,包装在另一个JSON对象中,最终包装在一个数组中。 See an example of what I'm talking about查看我正在谈论的示例

看看我指的是什么

I've used several codes but don't work.我使用了几个代码,但不起作用。

Like喜欢

org.json.JSONObject jsonFile = new org.json.JSONObject(_response);
        org.json.JSONObject key = jsonFile.getJSONObject("x_metadata");

test1 = key.getString("wp_GP_ID");

See Image Here:在此处查看图片:

在此处查看图片

I'm using the WordPress rest API so I'll be glad if anyone can assist me😪🙏🏾我正在使用 WordPress REST API,所以如果有人可以帮助我,我会很高兴😪🙏🏾

I would recommend using the Jackson json processor, it's simple and intuitive.我建议使用 Jackson json 处理器,它简单直观。

here is a example.这是一个例子。

//json string to JsonNode
String data = "{\"x_metadata\": {\"key_1\": \"text1\"," +
        " \"key_2\": true, \"key_3\": 100.0," +
        " \"key_array\": [\"text array 1\", \"text array 2\"]}}";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(data);
System.out.println(node);

//get object x_metadata
JsonNode nodeMetadata = node.get("x_metadata");
System.out.println(nodeMetadata);

//get value of a key
String valueKey = nodeMetadata.get("key_1").asText();
System.out.println(valueKey);

//get key type
System.out.println(nodeMetadata.getNodeType());
System.out.println(nodeMetadata.get("key_2").getNodeType());
System.out.println(nodeMetadata.get("key_3").getNodeType());
System.out.println(nodeMetadata.get("key_array").getNodeType());

//get keys
nodeMetadata.fieldNames().forEachRemaining(System.out::println);

pom.xml dependency. pom.xml 依赖项。

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.3</version>
 </dependency>

here more info about Jackson: https://www.baeldung.com/jackson这里有更多关于杰克逊的信息: https ://www.baeldung.com/jackson

I hope it helps you.我希望它对你有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM