I have oldId
and newId
and I want to replace oldId
with newId
.
public static void main(String[] args) {
String jsonString = "{\"user_id\":{\"long\":876},\"client_id\":{\"int\":0},\"affinity\":[{\"try\":{\"long\":55787693},\"scoring\":{\"float\":0.19}},{\"try\":{\"long\":1763},\"scoring\":{\"float\":0.0114}}]}";
// some other json strings -
// String jsonString = "{\"user_id\":{\"string\": \"876\"},\"client_id\":{\"int\":0},\"affinity\":[{\"try\":{\"long\":55787693},\"scoring\":{\"float\":0.19}},{\"try\":{\"long\":1763},\"scoring\":{\"float\":0.0114}}]}";
// String jsonString = "{\"user_id\": \"876\", \"client_id\":{\"int\":0},\"affinity\":[{\"try\":{\"long\":55787693},\"scoring\":{\"float\":0.19}},{\"try\":{\"long\":1763},\"scoring\":{\"float\":0.0114}}]}";
// String jsonString = "{\"user_id\": 876, \"client_id\":{\"int\":0},\"affinity\":[{\"try\":{\"long\":55787693},\"scoring\":{\"float\":0.19}},{\"try\":{\"long\":1763},\"scoring\":{\"float\":0.0114}}]}";
// String jsonString = "{\"user_id\": null, \"client_id\":{\"int\":0},\"affinity\":[{\"try\":{\"long\":55787693},\"scoring\":{\"float\":0.19}},{\"try\":{\"long\":1763},\"scoring\":{\"float\":0.0114}}]}";
String newResponse = changeJsonString(jsonString, "876", "54321");
System.out.println(newResponse);
}
private static String changeJsonString(String originalResponse, String oldId, String newId) {
return originalResponse.replaceAll(String.valueOf(oldId), String.valueOf(newId));
}
With the above code I have, it will print newResponse
as -
{\"user_id\":{\"long\":54321},\"client_id\":{\"int\":0},\"affinity\":[{\"matter\":{\"long\":5575432193},\"scoring\":{\"float\":0.19}},{\"try\":{\"long\":1763},\"scoring\":{\"float\":0.0114}}]}
If you see closely, two fields got change, one is user_id
and second is matter
since replaceAll
will replace everything to a new one.
- user_id 876 got change to 54321
- matter 55787693 got change to 5575432193
What I am looking for is - It should only replace the full number to a new number instead of modifying any number in the middle to a new number. As an example - user_id
876
is a full number so it should replace 876
only to 54321
notmatter
in which 876 is in the middle.
In general, I want to replace a number to a new number completely. I don't want to replace something in the middle of it. Is there any way to do this?