gpt4 book ai didi

java - 使用HashMap JAVA覆盖JSON

转载 作者:行者123 更新时间:2023-11-30 07:13:44 24 4
gpt4 key购买 nike

我知道有很多 stackoverflow 问题和答案可以帮助解决这个问题。我的问题不是关于修复而是关于正确书写。我需要人们的意见,我才能做出更好的决定。

这是 JSON 示例:

"SearchResult": {
"usersList": [
{
"name": "userId",
"value": "1009"
},
{
"name": "userName",
"value": "{userName}"
},
{
"name": "userUrl",
"value": "{userUrl}"
}
]
}

我们进行了测试,覆盖此 JSON 并将其作为 resultList 发送到应用程序。

为了覆盖,我们将值赋给HashMap:

public Map<String, String> createUserList(String userName, String userUrl) {
Map<String, String> putsValue = new HashMap<String, String>();
//putsValue.put("{userName}", userName);
putsValue.put("\\{userName\\}", userName);
putsValue.put("\\{userUrl\\}", userUrl);
return putsValue;
}

问题是我什么时候使用

putsValue.put("{userName}", userName);

当我尝试使用以下代码解析 JSON 时:

String jsonTemplate = "fileName.json";
JSONTokener tokener = new JSONTokener(new FileReader(jsonTemplate));
JSONObject root = new JSONObject(tokener);
parsedJson = root.toString();

for (Map.Entry<String, String> putsValue: putsValue.entrySet()) {
parsedJson = parsedJson
.replaceAll(putsValue.getKey(), putsValue.getValue());
}

我收到此错误

java.util.regex.PatternSyntaxException: Illegal repetition
{userName}
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.closure(Unknown Source)
at java.util.regex.Pattern.sequence(Unknown Source)
at java.util.regex.Pattern.expr(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)

如何找到这样的标签:

putsValue.put("{userName}", userName);

并替换值,我不想这样做

putsValue.put("\\{userName\\}", userName);

最佳答案

您可以尝试Pattern.quote(String)如下:

parsedJson = parsedJson
.replaceAll(Pattern.quote(putsValue.getKey()), putsValue.getValue());

关于java - 使用HashMap JAVA覆盖JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38769033/

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