Replies: 2 comments 1 reply
-
Try below? import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class JsonModifier {
private static void removeItemsParents(JsonNode node, JsonNode parent) {
if (node.isObject()) {
ObjectNode objectNode = (ObjectNode) node;
JsonNode itemsNode = objectNode.get("items");
if (itemsNode != null) {
// Check if the current node has "errorMessages" to preserve, then handle "items"
if (itemsNode.isObject()) {
// If "items" is an object with "errorMessage", preserve it
JsonNode errorMessage = itemsNode.get("errorMessage");
if (errorMessage != null) {
objectNode.remove("items");
objectNode.set("errorMessage", errorMessage);
}
} else if (itemsNode.isArray()) {
// If "items" is an array, remove or transform as needed
objectNode.remove("items");
}
}
// Recurse for children of this object
node.fields().forEachRemaining(entry -> removeItemsParents(entry.getValue(), node));
} else if (node.isArray()) {
ArrayNode arrayNode = (ArrayNode) node;
for (JsonNode child : arrayNode) {
removeItemsParents(child, node);
}
}
}
public static void main(String[] args) {
try {
String jsonString = "{ \"yourJson\": \"goesHere\" }"; // Your JSON string
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(jsonString);
removeItemsParents(rootNode, null);
String modifiedJsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
System.out.println(modifiedJsonString);
} catch (Exception e) {
e.printStackTrace();
}
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
Seems like its removing the first instance of items which in turn is removing the nested error message. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Greetings everyone!
I am in a bit of a pickle in that I can't figure out how to recursively traverse and preserve "errorMessages" while removing these nested "items" parents. Also "items" is an arraynode for the first instance but an object for the rest which makes it even more confusing. Any help is greatly appreciated! God Bless!!
Beta Was this translation helpful? Give feedback.
All reactions