有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

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

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