我想使用jackson修改TextNode
的值
但API中没有这样的方法
然后我尝试使用反射来克服限制:
public class TestModify {
public static void main(final String[] args) throws JsonProcessingException, IOException,
NoSuchFieldException, SecurityException, IllegalArgumentException,
IllegalAccessException {
final String json = "[{},\"123123\",\"12456\"]";
final ObjectMapper mapper = new ObjectMapper();
final JsonNode node = mapper.readTree(json);
final Iterator<JsonNode> nodes = node.elements();
while (nodes.hasNext()) {
final JsonNode n = nodes.next();
if (n instanceof TextNode) {
final Field f = TextNode.class.getDeclaredField("_value");
f.setAccessible(true);
f.set(n, "updated");
}
System.out.println(n.getClass());
}
System.out.println(node);
}
}
代码似乎工作正常,println
显示:
class com.fasterxml.jackson.databind.node.ObjectNode
class com.fasterxml.jackson.databind.node.TextNode
class com.fasterxml.jackson.databind.node.TextNode
[{},"updated","updated"]
那么为什么原始API中没有更新方法?
答案 0 :(得分:3)
这一定是设计决定。 TextNode
表示JSON字符串。像Java String
一样,他们很可能认为它应该是不可变的。
您可以简单地用新的实例替换现有的TextNode
个实例。