我想从json中删除一些值。 json格式如下:
{
"cod": "200",
"message": 0.0135,
"cnt": 40,
"list": [
{
"dt": 1545598800,
"main": {
"temp": 267.03,
"temp_min": 258.629,
"temp_max": 267.03,
"pressure": 741.31,
"sea_level": 1034.85,
"grnd_level": 741.31,
"humidity": 72,
"temp_kf": 8.4
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01n"
}
]
}
我想从json中删除一些数据。 如何在天气中删除ID,图标? 我尝试这个:
(ObjectNode) rootNode.get("list").get(i).get("weather")).remove("id");
但它不正确,并且会发生此错误:
com.fasterxml.jackson.databind.node.ArrayNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode
答案 0 :(得分:1)
问题是rootNode.get("list").get(i).get("weather")
将返回weather
数组
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01n"
}
]
然后获取第一个ObjectNode并删除id
(ObjectNode) rootNode.get("list").get(i).get("weather").get(0).remove("id");
答案 1 :(得分:0)
尝试以下代码可能会起作用。首先将JsonNode转换为ObjectNode
JsonNode yourJsonNode;
List<String> fieldsTobeRemoved = Arrays.asList("a","b");
if (!yourJsonNode.isMissingNode() && yourJsonNode instanceof ObjectNode && null != fieldsTobeRemoved) {
ObjectNode yourObjectNode = (ObjectNode) yourJsonNode;
fieldsToBeRemoved.forEach(field -> yourObjectNode.remove(field));
}