Помимо использования удобных библиотек редактирования json, вы можете использовать regexp:
String inputJson = "{\r\n" +
" \"fullName\" : \"Hamo\",\r\n" +
" \"staff\" : false,\r\n" +
" \"supr\" : true,\r\n" +
" \"permissions\" : [ \"Perm1\", \"Perm2\" ],\r\n" +
" \"services\" : [ \"Serv1\", \"Serv2\" ],\r\n" +
" \"authToken\" : \"1234567890abcdefghaijklmnopqrstuvwxyz\",\r\n" +
" \"customerId\" : 12345,\r\n" +
" \"clients\" : [ 1, 3, 8 ],\r\n" +
" \"wts\" : false,\r\n" +
//yyyy-MM-dd
" \"testDate\" : \"1982-09-21\"\r\n" +
"}";
String desiredAuthToken = "anyAuthTokenYouWant";
inputJson.replaceAll("(\"authToken\"\\s*:\\s*\")\\w*", "$1" + desiredAuthToken);
Вот объяснение:
"(\"authToken\"\\s*:\\s*\")\\w*";
( – start of a first capturing group
\"authToken\" – matches "authToken" string
\\s* – 0 to N whitespaces (including normal spaces, tabulations, etc.)
: – matches a single colon
\\s* – 0 to N whitespaces again
) – end of the capturing group
\\w* – matches 0 to N alphanumeric characters. You may want to replace it with a different regexp, that suits you needs in a better way.
Наконец, вы заменяете все соответствующее выражение с "$1" + desiredAuthToken
, где $1
- это в основном содержимое первой группы захвата. (Это \"authToken\" : \"
в данном случае).