Java在JSON字符串中提取值
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonExample {
public static void main(String[] args) {
String jsonString = "{\n" +
" \"Interval\": \"min\",\n" +
" \"Data\": [{\n" +
" \"Resource\": \"all\",\n" +
" \"CdnData\": [{\n" +
" \"Metric\": \"flux\",\n" +
" \"DetailData\": [{\n" +
" \"Time\": \"2024-07-16 00:00:00\",\n" +
" \"Value\": 5.2681682E9\n" +
" }, {\n" +
" \"Time\": \"2024-07-16 00:01:00\",\n" +
" \"Value\": 6.142274E9\n" +
" }, {\n" +
" \"Time\": \"2024-07-16 00:02:00\",\n" +
" \"Value\": 6.142274E9\n" +
" }, {\n" +
" \"Time\": \"2024-07-16 16:34:00\",\n" +
" \"Value\": 1.84028283E10\n" +
" }, {\n" +
" \"Time\": \"2024-07-16 16:35:00\",\n" +
" \"Value\": 1.58992701E10\n" +
" }, {\n" +
" \"Time\": \"2024-07-16 16:36:00\",\n" +
" \"Value\": 1.64644905E10\n" +
" }, {\n" +
" \"Time\": \"2024-07-16 16:37:00\",\n" +
" \"Value\": 1.58937733E10\n" +
" }, {\n" +
" \"Time\": \"2024-07-16 16:38:00\",\n" +
" \"Value\": 1.71402732E10\n" +
" }],\n" +
" \"SummarizedData\": {\n" +
" \"Name\": \"sum\",\n" +
" \"Value\": 9.0348401E12\n" +
" }\n" +
" }]\n" +
" }],\n" +
" \"RequestId\": \"f397bdfa-8358-448e-9428-acce3e88e2d7\"\n" +
"}";
try {
// 创建ObjectMapper实例
ObjectMapper objectMapper = new ObjectMapper();
// 解析JSON字符串为JsonNode
JsonNode rootNode = objectMapper.readTree(jsonString);
// 导航到SummarizedData的Value
JsonNode summarizedDataNode = rootNode.path("Data").get(0)
.path("CdnData").get(0)
.path("SummarizedData")
.path("Value");
// 获取Value值
double value = summarizedDataNode.asDouble();
// 输出结果
System.out.println("SummarizedData的Value值: " + value);
} catch (Exception e) {
e.printStackTrace();
}
}
}