Reputation: 7594
I have a Json object as follows:
{ "name": "john doe", "ssn": "111-22-3333"}
I want to replace the ssn
field with empty string. I know I can do a straight replace, but i am trying to build a general purpose lib that can replace elements in a json object.
I tried to do this using jackson's JsonPointer
implementation.
JsonPointer pointer = JsonPointer.compile(path);
JsonNode root = null;
root = mapper.readTree(payload);
JsonNode targetNode = root.at(pointer);
if(!pointer.matches()) {
throw new IOException("Pointer did not match");
}
JsonNode parentNode = root.at(pointer.head());
JsonNode replacementNode = null;
if (targetNode.isTextual()) {
replacementNode = TextNode.valueOf(config.getString(REPLACEMENT_VALUE_STRING));
} else if (targetNode.isInt()) {
replacementNode = IntNode.valueOf(config.getInt(REPLACEMENT_VALUE_INT));
} else if (targetNode.isBigInteger()) {
BigInteger bi = BigInteger.valueOf(config.getInt(REPLACEMENT_VALUE_INT));
replacementNode = BigIntegerNode.valueOf(bi);
} else if (targetNode.isFloat()) {
replacementNode = FloatNode.valueOf(config.getDouble(REPLACEMENT_VALUE_INT).floatValue());
} else if (targetNode.isDouble()) {
replacementNode = DoubleNode.valueOf(config.getDouble(REPLACEMENT_VALUE_DOUBLE));
} else if (targetNode.isArray()) {
replacementNode = mapper.createArrayNode();
}
if (parentNode.isObject()) {
((ObjectNode)parentNode).set(pointer.getMatchingProperty(), replacementNode);
} else if (parentNode.isArray()) {
((ArrayNode)parentNode).set(pointer.tail().getMatchingIndex(), replacementNode);
}
return root;
However, the problem is that JsonPointer
does not tell me if there is an actual match. If there is no match, then it returns an empty node. And then my code ends up adding an extra field to the json.
For eg,
INPUT: {"name": "jon", "age": 30}
OUTPUT: `{"name": "jon", "age": 30, "ssn": null}
I tried to read the Jackson JsonPointer documentation, but it is not helpful at all.
Upvotes: 0
Views: 2704
Reputation: 7594
I figured out the issue. Instead of using pointer.matches()
I need to examine the result of the match and see if it is an empty node.
Upvotes: 0