Java 使用 Jackson 库解析 JSON 数据获取 targets 数据
你可以使用 Java 中 JSON 库来解析 JSON 数据,比如使用 Jackson 库。以下是一个示例代码,展示如何获取 JSON 数据中 report 下的 targets 数据:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JSONParser {
public static void main(String[] args) {
String jsonData = '{"report": {"targets": ["target1", "target2"]}}';
try {
// 创建 ObjectMapper 对象
ObjectMapper objectMapper = new ObjectMapper();
// 解析 JSON 数据
JsonNode rootNode = objectMapper.readTree(jsonData);
// 获取 report 节点下的 targets 节点
JsonNode targetsNode = rootNode.path('report').path('targets');
// 遍历 targets 节点的数据
for (JsonNode targetNode : targetsNode) {
String target = targetNode.asText();
System.out.println(target);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
上面的代码中,我们首先创建了一个 ObjectMapper 对象,然后使用 readTree() 方法解析 JSON 数据。接下来,我们使用 path() 方法来获取 report 节点下的 targets 节点。最后,我们使用 foreach 循环遍历 targets 节点的数据,并打印出来。
请注意,以上代码依赖于 Jackson 库,你需要将其添加到你的项目中。你可以通过 Maven 或 Gradle 等构建工具来添加 Jackson 库的依赖。
原文地址: https://www.cveoy.top/t/topic/gsDC 著作权归作者所有。请勿转载和采集!