Java中是否有JSON库可以轻松替换JSON树中的值,在JSON树中,我只知道值,而不知道映射到它的字段/键?
我有一个JsonNode(Jackson)对象,我想替换其中的一个特定值。是否有Json库可以帮助查找映射到特定值的字段,或者我需要递归遍历它 例如,我想用一些对象替换下面json中的占位符。我想知道是否有一个来自Jackson或其他库的API,我可以利用它来完成一行。请注意,我不知道要搜索的字段,但我知道该值为“{replaceValueHereWithAnyObject}”Java中是否有JSON库可以轻松替换JSON树中的值,在JSON树中,我只知道值,而不知道映射到它的字段/键?,java,json,kotlin,jackson,Java,Json,Kotlin,Jackson,我有一个JsonNode(Jackson)对象,我想替换其中的一个特定值。是否有Json库可以帮助查找映射到特定值的字段,或者我需要递归遍历它 例如,我想用一些对象替换下面json中的占位符。我想知道是否有一个来自Jackson或其他库的API,我可以利用它来完成一行。请注意,我不知道要搜索的字段,但我知道该值为“{replaceValueHereWithAnyObject}” replace(…)似乎只接受字段作为输入,并替换该字段的值。在我的例子中,我不知道哪个字段映射到我要替换的已知值。我
replace(…)似乎只接受字段作为输入,并替换该字段的值。在我的例子中,我不知道哪个字段映射到我要替换的已知值。我不知道有一个库(顺便说一句,请求库推荐很可能会使一个问题以“主题外”的形式结束),但自己做这件事并不难。下面是一段用于递归遍历和就地编辑的代码。它只查看文本节点,替换始终是文本节点,但您可以根据需要调整它
// Walk the JSON tree and modify textual fields in-place.
public static void transformTextFields(JsonNode node, Function<String, String> transformer) {
if (node.isObject()) {
// take a snapshot of the field names to avoid concurrent modification
final List<String> fieldNames = new ArrayList<>(node.size());
node.fieldNames().forEachRemaining(fieldNames::add);
for (String fieldName : fieldNames) {
final JsonNode child = node.get(fieldName);
if (child.isContainerNode()) {
transformTextFields(child, transformer);
} else if (child.isTextual()) {
final String oldValue = child.textValue();
((ObjectNode) node).set(fieldName, new TextNode(transformer.apply(oldValue)));
}
}
} else if (node.isArray()) {
for (int i = 0; i < node.size(); i++) {
final JsonNode child = node.get(i);
if (child.isContainerNode()) {
transformTextFields(child, transformer);
} else if (child.isTextual()) {
final String oldValue = child.textValue();
((ArrayNode) node).set(i, new TextNode(transformer.apply(oldValue)));
}
}
}
}
// Walk the JSON tree and modify textual fields in-place.
public static void transformTextFields(JsonNode node, Function<String, String> transformer) {
if (node.isObject()) {
// take a snapshot of the field names to avoid concurrent modification
final List<String> fieldNames = new ArrayList<>(node.size());
node.fieldNames().forEachRemaining(fieldNames::add);
for (String fieldName : fieldNames) {
final JsonNode child = node.get(fieldName);
if (child.isContainerNode()) {
transformTextFields(child, transformer);
} else if (child.isTextual()) {
final String oldValue = child.textValue();
((ObjectNode) node).set(fieldName, new TextNode(transformer.apply(oldValue)));
}
}
} else if (node.isArray()) {
for (int i = 0; i < node.size(); i++) {
final JsonNode child = node.get(i);
if (child.isContainerNode()) {
transformTextFields(child, transformer);
} else if (child.isTextual()) {
final String oldValue = child.textValue();
((ArrayNode) node).set(i, new TextNode(transformer.apply(oldValue)));
}
}
}
}
transformTextFields(myJsonNode, fieldValue -> replaceMyPlaceholder(fieldValue));