为什么TextNode没有更新值(set)方法?

时间:2014-10-14 03:47:47

标签: java json jackson

我想使用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 个答案:

答案 0 :(得分:3)

这一定是设计决定。 TextNode表示JSON字符串。像Java String一样,他们很可能认为它应该是不可变的。

您可以简单地用新的实例替换现有的TextNode个实例。