gpt4 book ai didi

java - 如何从 JSON 中嵌入的 JSON 中提取属性?

转载 作者:行者123 更新时间:2023-11-29 05:25:10 24 4
gpt4 key购买 nike

这是我从 URL 返回的 JSON 字符串,我想从下面的 JSON 字符串中提取 highDepth 值。

{
"description": "",
"bean": "com.hello.world",
"stats": {
"highDepth": 0,
"lowDepth": 0
}
}

我在这里使用 GSON,因为我是 GSON 的新手。如何使用 GSON 从上述 JSON 字符串中提取 highDepth

String jsonResponse = restTemplate.getForObject(url, String.class);

// parse jsonResponse to extract highDepth

最佳答案

你创建了一对 POJO

public class ResponsePojo {    
private String description;
private String bean;
private Stats stats;
//getters and setters
}

public class Stats {
private int highDepth;
private int lowDepth;
//getters and setters
}

然后您可以在 RestTemplate#getForObject(..) 调用中使用它

ResponsePojo pojo = restTemplate.getForObject(url, ResponsePojo.class);
int highDepth = pojo.getStats().getHighDepth();

不需要 Gson。


如果没有 POJO,由于 RestTemplate 默认使用 Jackson,您可以将 JSON 树检索为 ObjectNode

ObjectNode objectNode = restTemplate.getForObject(url, ObjectNode.class);
JsonNode highDepth = objectNode.get("stats").get("highDepth");
System.out.println(highDepth.asInt()); // if you're certain of the JSON you're getting.

关于java - 如何从 JSON 中嵌入的 JSON 中提取属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22954110/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com