java - 设置特定的 JSONPATH 元素值

标签 java jsonpath

我试图从以下 JSON 文本设置作者值,但我的代码正在删除 json 文本的所有其他子项。

   {
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "XXXXXXXXXXXXXXXXX",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": XXXXXXXXXXXXXXXXXXXXX
            },
            {
                "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
}

我尝试将第一本书中的作者更新为如下所示的其他值。

Object updatedJson = JsonPath.using(configuration).parse(jsonInput).json();
String jayPath = "$..book[0].author";
String tagValue = "ReplacedText";
                String jsonToParse = updatedJson.toString();
                updatedJson = JsonPath.parse(jsonToParse).set(jayPath, tagValue).json();

设置步骤后,我的 json 仅包含 book[1] 的内容,如下所示。请告知如何获得我提供的整个 json 输入以及替换值作为输出。

{store={book=[{"category"=reference, author=XXXXXXXXXXXXXXXXX, title=Sayings of the Century, price=8.95}

问候, 萨提斯。

最佳答案

无需将 DocumentContext 转换为 json 也能正常工作

public static void main(String[] args) {
    DocumentContext json = JsonPath.using(configuration).parse(jsonInput);
    String jayPath = "$..book[0].author";
    String tagValue = "ReplacedText";
    System.out.println(json.set(jayPath, tagValue).jsonString());
}

关于java - 设置特定的 JSONPATH 元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41808282/

相关文章:

JsonPath:如果满足条件,则选择根级别字段

java - 为什么我的 Inner Join 查询没有返回任何内容?

java - 更新记录 if somcolumn! ="somevalue",使用 Hibernate saveorupdate()

java - JUnit:调用每个@Test 方法之前的新实例。有什么好处?

json - 使用 JSONPath 按名称过滤 json 属性

java - 如何从 JSON 字符串获取值的所有 JSON 路径的列表?

javascript - AJAX 调用失败,url 路径是否正确?

java - Spring 集成 Java DSL : specify custom deserializer

json.net - Newtonsoft JSON.Net SelectToken 问题

mysql - 在数组中搜索 JSON 数据类型的对象属性时出现问题