这里我发现了两个问题,一是JSON格式不正确。应该是:
{
"distance":[
{
"weight": 60,
"unit": "km"
},
{
"weight": 100,
"unit": "m"
}
]
}
或
[
{
"weight": 60,
"unit": "km"
},
{
"weight": 100,
"unit": "m"
}
]
另外,你没有明确提到你的POJO。您可以通过多种方式实现此响应。为简单起见,我假设它是简单的Map。
但是,我们首先需要使这个字符串格式正确。
String jsonStr = "\"distance\":[\n" +
" {\n" +
" \"weight\": 60,\n" +
" \"unit\": \"km\"\n" +
" },\n" +
" {\n" +
" \"weight\": 100,\n" +
" \"unit\": \"m\"\n" +
" }\n" +
"]";
jsonStr = jsonStr.substring(jsonStr.indexOf(":") + 1);
创建一个类:
@Data
public class Distance {
private Double weight;
private String unit;
}
这里我使用 lombok 作为 getter 和 setter。
将 JSON 字符串解析为 list of Distance:
ObjectMapper objectMapper = new ObjectMapper();
List<Distance> distances = objectMapper.readValue(jsonStr, new TypeReference<List<Distance>>(){});
现在您可以将此列表转换为您想要的响应。将此响应转换为Map:
Map<String, Double> response = distances.stream().collect(Collectors.toMap(Distance::getUnit, Distance::getWeight));
或者,您也可以将其转换为List<Pair<String, Double>>:
List<Pair<String, Double>> response = new ArrayList<>();
distances.forEach(distance -> {
response.add(new Pair(distance.getUnit(), distance.getWeight()));
});
编码愉快...