我有以下 JSON:
{
"code":1000,
"message":"Success",
"data":{
"results":[
{
"lineId":"C4000LG2020253739",
"lineDiagnostics":{
"C4000LG2020253739":{
"ap":{
"broadbanddsthroughput":{
"broadbandDsThroughput":[
{
"average":104830,
"std":0,
"detection":0,
"numErrorFreeSamples":1,
"sampleMaxPercentile":107673,
"latestSampleTimestamp":1698160893000,
"sampleMax":107673,
"url":"http://blah-blah.com",
"videoQuality":7,
"serviceDetection":-1,
"percentile":[
104830
],
"latestSample":104830,
"primaryIp":"205.171.3.100",
"speedTestTrafficMB":56.9910995
}
]
},
"broadbandusthroughput":{
"broadbandUsThroughput":[
{
"average":37828,
"std":0,
"numErrorFreeSamples":1,
"sampleMaxPercentile":38393,
"latestSampleTimestamp":1698160893000,
"sampleMax":38393,
"url":"http://blah-blah.com",
"serviceDetection":-1,
"percentile":[
37828
],
"latestSample":37828,
"primaryIp":"205.171.3.100",
"speedTestTrafficMB":21.8231345
}
]
}
},
"interface":{
},
"station":{
},
"multiWan":{
}
}
},
"analysisDay":20231024
}
]
}
}
在Diagnostics行下,我们有“C4000LG2020253739”:{...},我需要该对象内部的内容进行进一步计算,有人可以告诉我如何实现这一点吗?
我正在使用 Jackson 将 JSON 值映射到 Java 类。
注意:这个特定的字符串值“C4000LG2020253739”:{...}将随着每个微服务调用而改变(而不是这个{...}中的内容),所以我面临着创建通用Java类的问题这个 JSON 结构。
我正在使用 Jackson 将 JSON 值映射到 Java 类:
public class Class1{
//historical speed response structure : map from json response
String code;
String message;
@JsonProperty("data")
DataSpeeds dataSpeeds;
...}
public class DataSpeeds {
@JsonProperty("results")
List<Results> results;
@JsonProperty("lineId")
String lineId;
...}
public class Results {
String lineId;
@JsonProperty("lineDiagnostics")
LineDiagnostics lineDiagnostics;
...}
public class LineDiagnostics {
@JsonProperty("ap")
Ap ap;
...}
在 LineDiagnostics 对象内部,我需要从 JSON 映射“C4000LG2020253739”:{...},如何做到这一点?有什么指示吗?
至少你可以将 json 反序列化为
Map
并从中检索所需的数据。
public static Map<String, Object> getResultByLineId(File file, String lineId) throws IOException {
ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<String, Object>> typeRef = new TypeReference<>() {
};
Map<String, Object> map = mapper.readValue(file, typeRef);
Map<String, Object> data = (Map<String, Object>) map.getOrDefault("data", Map.of());
List<Object> results = (List<Object>) data.getOrDefault("results", List.of());
return results.stream()
.map(result -> (Map<String, Object>) result)
.filter(result -> lineId.equals(result.get("lineId")))
.map(result -> result.getOrDefault("lineDiagnostics", List.of()))
.map(lineDiagnostics -> (Map<String, Object>) lineDiagnostics)
.findFirst().orElse(Map.of());
}
但我建议您构建一个模型并使用它而不是
Map
。