天天看點

JsonUtil----json工具類一、簡介二、代碼

一、簡介

二、代碼

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分鐘.