I think that you don't want to change the object being passed to the method, So you have made a deep copy. And you want to return a new JSON object.
Am I right so far? If yes, As you have made the deep copy, use it, loop through each element of the array of your concern and replace the Node value with what you desire.
private static JsonNode attachmentConversion(JsonNode object){
final String ATTACHMENT_POINTER = "/RESULTS/ATTACHMENTS/ATTACHMENT"; //Path to the array
ObjectNode OUTPUT = object.deepCopy();
OUTPUT.remove("DETAILS");
//Validate is an array - It properly fetches the array
if(OUTPUT.at(ATTACHMENT_POINTER).isArray()){
int counter=0;
//Loop through attachment array - It properly fethes each object in the array
for(final JsonNode objNode : OUTPUT.at(ATTACHMENT_POINTER)){
((ObjectNode)objNode).replace("ATTACH_CONTENT", xmlToJson.parseXmlToJson(objNode.get("ATTACH_CONTENT"));
}
}
return new ObjectMapper()
.createObjectNode()
.set("customertopology", OUTPUT);
}
Instead of providing entire path, you can do
OUTPUT.get("RESULTS").get("ATTACHMENTS").get("ATTACHMENT");
This should return the array. Full code using fasterxml
String json = "{\n" +
" \"RESULTS\": {\n" +
" \"ATTACHMENTS\": {\n" +
" \"ATTACHMENT\": [{\"key\": 1}, {\"key\": 2}]\n" +
" }\n" +
" }\n" +
"}";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(json);
node.get("RESULTS").get("ATTACHMENTS").get("ATTACHMENT").forEach(obj -> {
System.out.println(obj.get("key"));
});
Also following code print true for me.
System.out.println(node.at("/RESULTS/ATTACHMENTS/ATTACHMENT").isArray());
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.
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);