使用JsonPath更新数组元素

时间:2015-12-22 17:59:12

标签: arrays replace element jsonpath

我正在尝试使用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')]

找到该元素

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

         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位。有没有办法真正替换数组元素?

0 个答案:

没有答案