我试图从以下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只有下面的书[1]的内容。请告知我如何获得我给出的整个json输入和替换值作为输出。
{store={book=[{"category"=reference, author=XXXXXXXXXXXXXXXXX, title=Sayings of the Century, price=8.95}
此致 Sathish所在。
答案 0 :(得分:3)
无需将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());
}