[英]Simple way to add double quote in a JSON String
我正在嘗試寫一些返回搜索建議結果的東西。
假設我有一個像這樣的字符串:
"[Harry,[harry potter,harry and david]]"
格式類似於[A_STRING,A_STRING_ARRAY_HERE]。
但是我希望輸出格式像
[ "Harry",["harry potter","harry and david"]]
這樣我就可以將其放入HTTP響應正文中。
有沒有簡單的方法可以執行此操作,我不想從頭開始為一個非常簡單的String添加“”。
演示
String text = "[Harry,[harry potter,harry and david]]";
text = text.replaceAll("[^\\[\\],]+", "\"$0\"");
System.out.println(text);
輸出: ["Harry",["harry potter","harry and david"]]
說明:
如果我理解正確,你要圍繞着系列的所有非[
-和- ]
-和- ,
字符用雙引號。 在這種情況下,您可以簡單地使用帶有正則表達式([^\\\\[\\\\],]+)
replaceAll
方法,其中
[^\\\\[\\\\],]
-代表一個非字符,不是[
或]
或,
(逗號) [^\\\\[\\\\],]+
- +
表示元素可以出現一次或多次 ,在這種情況下,它表示一個或多個不是[
或]
或的字符,
(逗號) 現在在替換中,我們可以用雙括號"$0"
包圍由$0
表示的第$0
組匹配(整個匹配)。 順便說一句,由於"
是字符串中的元字符(用於開始和結束字符串),因此,如果要創建其文字,我們需要對其進行轉義。為此,我們需要在其前面放置\\
,因此在其末尾表示"$0"
字符串需要寫為"\\"$0\\""
。
有關$0
使用的第0組的更多說明(引自https://docs.oracle.com/javase/tutorial/essential/regex/groups.html ):
還有一個特殊的組,組0,它始終代表整個表達式。
如果格式[A_STRING,A_STRING_ARRAY_HERE]
是一致的,只要任何字符串中都沒有逗號,則可以使用逗號作為分隔符,然后相應地添加雙引號。 例如:
public String format(String input) {
String[] d1 = input.trim().split(",", 2);
String[] d2 = d1[1].substring(1, d1[1].length() - 2).split(",");
return "[\"" + d1[0].substring(1) + "\",[\"" + StringUtils.join(d2, "\",\"") + "\"]]";
}
現在,如果您使用字符串"[Harry,[harry potter,harry and david]]"
調用format()
,它將返回您想要的結果。 並不是說我使用Apache Commons Lang庫中的StringUtils
類將String數組與分隔符連在一起。 您可以使用自己的自定義功能執行相同的操作。
程序的這種平靜效果(您可以對其進行優化):
//...
String str = "[Harry,[harry potter,harry and david]]";
public String modifyData(String str){
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '[' && str.charAt(i + 1) == '[') {
strBuilder.append("[");
} else if (str.charAt(i) == '[' && str.charAt(i + 1) != '[') {
strBuilder.append("[\"");
} else if (str.charAt(i) == ']' && str.charAt(i - 1) != ']') {
strBuilder.append("\"]");
} else if (str.charAt(i) == ']' && str.charAt(i - 1) == ']') {
strBuilder.append("]");
} else if (str.charAt(i) == ',' && str.charAt(i + 1) == '[') {
strBuilder.append("\",");
} else if (str.charAt(i) == ',' && str.charAt(i + 1) != '[') {
strBuilder.append("\",\"");
} else {
strBuilder.append(str.charAt(i));
}
}
return strBuilder.toString();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.