gpt4 book ai didi

JAVA:如何在嵌套的 JSONString 中查找子字符串的所有匹配项并替换为一些文本

转载 作者:行者123 更新时间:2023-12-04 07:58:20 26 4
gpt4 key购买 nike

JSON 字符串看起来像

{
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500,
"stamp" : "randomtestcasenumberwithtimeID2",
"case" : 1
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"stamp" : "randomtestcasenumberwithtimeID3"

},
}
}
我想替换 "stamp" 的所有实例带有一些静态的东西,例如 "stamp" : "Testing" .我该怎么办?请注意“stamp”的值是随机的。
所以在搜索并替换 stamp 的两个实例之后应该具有相同的值 "Testing"例子
    {
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500,
"stamp" : "Testing",
"case" : 1
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"stamp" : "Testing"

},
}
}

最佳答案

你可以试试这个:

String json = "<your-json-here>";
String newValue = "Testing";
String newJson = s.replaceAll("\"stamp\"\\s*:\\s*\"(.*)\"", String.format("\"stamp\" : \"%s\"", newValue));
甚至是这样的:
String s2 = s.replaceAll("(?<=\"stamp\")\\s*:\\s*\"(.*)(?=\")", ":\""+ newValue);

关于JAVA:如何在嵌套的 JSONString 中查找子字符串的所有匹配项并替换为一些文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66589317/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com