使用 JsonPath 更新数组元素

Update array element using JsonPath

提问人:florind 提问时间:12/23/2015 最后编辑:florind 更新时间:12/23/2015 访问量:1731

问:

我正在尝试在 Java 中使用 jayway 的 JsonPath 替换 Json 数组中的某个元素。例:

{
"store": {
    "book": [
        {
            "category": "reference",
            "author": "Nigel Rees",
            "title": "Sayings of the Century",
            "price": 8.95
        },
        {
            "category": "fiction",
            "author": "Evelyn Waugh",
            "title": "Sword of Honour",
            "price": 12.99
        },
        {
            "category": "fiction",
            "author": "Herman Melville",
            "title": "Moby Dick",
            "isbn": "0-553-21311-3",
            "price": 8.99
        },
        {
            "category": "fiction",
            "author": "J. R. R. Tolkien",
            "title": "The Lord of the Rings",
            "isbn": "0-395-19395-8",
            "price": 22.99
        }
    ],
    "bicycle": {
        "color": "red",
        "price": 19.95
    }
},
"expensive": 10

}

在这里,我希望能够替换数组中的第一本书。我可以使用此查询找到该元素$.store.book.[?(@.author =='Nigel Rees')]

然后,我使用此代码替换 this 节点:

         Configuration configuration =  Configuration.builder()
           .jsonProvider(new JacksonJsonNodeJsonProvider())
           .mappingProvider(new JacksonMappingProvider())
           .build();
        DocumentContext pbContext = JsonPath.using(configuration).parse(theAboveJson);
        pbContext.set("$.store.book.[?(@.author =='Nigel Rees')]", someOtherJson);

但我注意到,新节点不是替换,而是插入到 books 数组中的位置 0。有没有办法实际替换数组元素?

数组 替换 元素 JSONPATH

评论


答: 暂无答案