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" +
"}";
我有这个json字符串,我需要更改authToken值。仅具有名称“ authToken”,如何更改authToken的值?顺便说一句,反序列化不是一种选择,因此只能通过字符串操作来完成。
没有JSON类,仍然存在:
inputJson = inputJson.replaceFirst("(\"authToken\"\\s*:\\s*\")[^\"]*\"",
"$1" + authToken + "\"");
这假设authToken不包含美元$
。
除了使用方便的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\" : \"
。