解决方案
替换 -
while (hmIterator.hasNext()) {
Map.Entry mapElement = (Map.Entry)hmIterator.next();
//System.out.println(mapElement.getKey() + " : " + mapElement.getValue());
// inputJson.remove(mapElement.getKey().toString());
// inputJson.put(mapElement.getKey().toString(),mapElement.getValue());
System.out.println(json.replace(mapElement.getValue().toString(),"superman"));
}
与 -
while (hmIterator.hasNext()) {
Map.Entry mapElement = (Map.Entry) hmIterator.next();
String keyToBeSearchedFor = "\"" + mapElement.getKey().toString() + "\"";
StringBuffer buf = new StringBuffer(json);
// add 3 to start because of 2 double-quotes surrounding the key + 1 colon character after the double-quote after the key.
int start = json.indexOf(keyToBeSearchedFor) + mapElement.getKey().toString().length() + 3;
int end = start + mapElement.getValue().toString().length();
if (mapElement.getValue() instanceof String) {
// if the value is a String,we have to take the surrounding double quotes of the value into account.
end += 2;
stringToBeReplaced = "\"superman\"";
}
//System.out.println("Substring about to be replaced with superman=" + json.substring(start,end));
buf.replace(start,end,stringToBeReplaced);
System.out.println(buf);
stringToBeReplaced = "superman"; // revert back to default value for subsequent iterations.
}
带有新代码片段的输出 -
document-uri-referrer
blocked-uri-inline
------------------------------------------
{"csp-report":{"blocked-uri":"inline","column-number":superman,"document-uri":"referrer","column":8016}}
{"csp-report":{"blocked-uri":"inline","column-number":8016,"document-uri":"superman","column":superman}}
{"csp-report":{"blocked-uri":"superman","column":8016}}
说明
在原始代码片段中,使用了 .replace()
,它用新字符串替换 所有 出现的子字符串。结果——
json.replace("8016","superman")
将所有出现的 8016
替换为 superman
,这不是我们想要的行为。 OP 已经提到,在每次迭代中,只有 1 次出现的值应替换为 superman
。
为了找到需要替换的子串的索引,我们可以利用这样一个事实,即在当前迭代中,要替换的子串将紧跟在键之后(带有2个双引号)。
注意事项
如果 JSON
中的多个键在 JSON
内的不同深度具有相同名称,则此解决方案可能不起作用。
例如 -
String json = "{\"csp-report\":{\"blocked-uri\":\"inline\",\"column-number\":8016,\"document-uri\":\"referrer\",\"column\":8016,\"node\":{\"column\":8016}}}";
本文链接:https://www.f2er.com/4618.html