我试图从以下 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/