设置特定的 JSONPATH 元素值
Set specific JSONPATH element value
我试图从以下 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());
}
我试图从以下 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());
}