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

       

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章