java为什么TextNode没有更新值(set)方法?
我想使用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中没有更新方法呢
# 1 楼答案
这一定是一个设计决定。一个
TextNode
代表一个JSON字符串。就像JavaString
一样,他们很可能决定它应该是不可变的您可以简单地用新实例替换现有的
TextNode
实例