I haven't tested this, but I think something like this would do what you want:
import org.codehaus.jackson.node.ObjectNode;
// ...
for (JsonNode personNode : rootNode) {
if (personNode instanceof ObjectNode) {
ObjectNode object = (ObjectNode) personNode;
object.remove("familyName");
object.remove("middleName");
}
}
You could also do this more efficiently using Jackon's raw parsing API, but the code would be a lot messier.
Answer from gsteff on Stack OverflowI haven't tested this, but I think something like this would do what you want:
import org.codehaus.jackson.node.ObjectNode;
// ...
for (JsonNode personNode : rootNode) {
if (personNode instanceof ObjectNode) {
ObjectNode object = (ObjectNode) personNode;
object.remove("familyName");
object.remove("middleName");
}
}
You could also do this more efficiently using Jackon's raw parsing API, but the code would be a lot messier.
ObjectMapper of Jackson gives solution with only few steps.
Save the json data in a file say 'data.json'. Copy following the code into a function without import statements and invoke the function. The resulting JSON will be written into a new file 'data1.json'.
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(new File("data.json"));
for (JsonNode node : jsonNode) {
((ObjectNode)node).remove("familyName");
((ObjectNode)node).remove("middleName");
}
objectMapper.writeValue(new File("data1.json"), jsonNode);
The problem is rootNode.get("list").get(i).get("weather") will return the weather array
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01n"
}
]
Then get the first ObjectNode and remove id
(ObjectNode) rootNode.get("list").get(i).get("weather").get(0).remove("id");
Try the below code it may work. First convert the JsonNode to 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));
}