一、简介
二、代码
2.1 makeupJsonStrByJsonKV(String oldStr, String keyValueJsonStr)
- 源码
-
/** * 将包含key的字符串使用json串替换 * 注意: 文本内容不能包含符号 # 如果需要扩展,可以将该分隔符抽出来 * * @param oldStr 如: 你的验证码是{code}, 有效期为{expire}分钟. * @param keyValueJsonStr {"code":"123456","expire":"10"} * @return 拼接好的字符串 如: 你的验证码是123456, 有效期为10分钟. */ public static String makeupJsonStrByJsonKV(String oldStr, String keyValueJsonStr) { String makeupContent = oldStr.replaceAll("\\{", "#").replaceAll("}", "#"); String[] splitNewOldContentArray = makeupContent.split("#"); makeupContent = makeupContent.replaceAll("#", ""); JSONObject jsonObject = JSONObject.fromObject(keyValueJsonStr); for (int i = 0; i < splitNewOldContentArray.length; i++) { if (i % 2 != 0) { String key = splitNewOldContentArray[i]; String value = jsonObject.get(key).toString(); makeupContent = makeupContent.replaceAll(key, value); } } return makeupContent; }
-
- 例子
-
public static void main(String[] args) { String oldStr = "你的验证码是{code}, 有效期为{expire}分钟."; String keyValueJsonStr = "{\"code\":\"123456\",\"expire\":\"10\"}"; System.out.println(makeupJsonStrByJsonKV(oldStr, keyValueJsonStr)); }
-
- 结果
-
你的验证码是123456, 有效期为10分钟.
-