我想使用杰克逊修改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中没有更新方法呢?
发布于 2014-10-14 04:18:52
这一定是设计上的决定。TextNode表示一个JSON字符串。就像一个Java String一样,他们很可能认为它应该是不可变的。
您可以简单地用新实例替换现有的TextNode实例。
https://stackoverflow.com/questions/26352325
复制相似问题