[英]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.