Boston Star Boston Star - 1 year ago 70
Java Question

JSON overwrite using HashMap JAVA

I understand there are many stackoverflow question and answer can help to fix this. My Question is not about fixing but writing properly. I need people view and I make better decision.

Here is JSON example :

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

We have test that overwrite this JSON and send as
to application.

For overwrite we have put value to

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;

Question is When I used

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

When I try to parse JSON using following code :

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());

I am getting this error

java.util.regex.PatternSyntaxException: Illegal repetition
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)

How I can find tags like this:

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

And replace value I don't want to do this way

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

Answer Source

You can try Pattern.quote(String) as next:

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