简体   繁体   English

在JSON字符串中添加双引号的简单方法

[英]Simple way to add double quote in a JSON String

I am trying to write something that returns some search suggestion result. 我正在尝试写一些返回搜索建议结果的东西。

Suppose I have an string like this : 假设我有一个像这样的字符串:

"[Harry,[harry potter,harry and david]]"

The format is like [A_STRING,A_STRING_ARRAY_HERE]. 格式类似于[A_STRING,A_STRING_ARRAY_HERE]。

But I wany the output format to be like 但是我希望输出格式像

[ "Harry",["harry potter","harry and david"]]

so that I can put it into the HTTP Response Body. 这样我就可以将其放入HTTP响应正文中。

Is there a simple way to do this, I don't want to add "" for a very single String from scratch . 有没有简单的方法可以执行此操作,我不想从头开始为一个非常简单的String添加“”。

Demo 演示

String text = "[Harry,[harry potter,harry and david]]";
text = text.replaceAll("[^\\[\\],]+", "\"$0\"");

System.out.println(text);

Output: ["Harry",["harry potter","harry and david"]] 输出: ["Harry",["harry potter","harry and david"]]


Explanation: 说明:
If I understand you correctly you want to surround series of all non- [ -and- ] -and- , characters with double quotes. 如果我理解正确,你要围绕着系列的所有非[ -和- ] -和- ,字符用双引号。 In that case you can simply use replaceAll method with regex ([^\\\\[\\\\],]+) in which which 在这种情况下,您可以简单地使用带有正则表达式([^\\\\[\\\\],]+) replaceAll方法,其中

  • [^\\\\[\\\\],] - represents one non character which is not [ or ] or , (comma) [^\\\\[\\\\],] -代表一个非字符,不是[], (逗号)
  • [^\\\\[\\\\],]+ - + means that element before it can appear one or more times , in this case it represents one or more characters which are not [ or ] or , (comma) [^\\\\[\\\\],]+ - +表示元素可以出现一次或多次 ,在这种情况下,它表示一个或多个不是[]或的字符, (逗号)

Now in replacement we can just surround match from group 0 (entire match) represented by $0 with double brackets "$0" . 现在在替换中,我们可以用双括号"$0"包围由$0表示的第$0 匹配(整个匹配)。 BTW since " is metacharacter in String (it is used to start and end string) we need to escape it if we want to create its literal. To do so we need to place \\ before it so at the end it String representing "$0" needs to be written as "\\"$0\\"" . 顺便说一句,由于"是字符串中的元字符(用于开始和结束字符串),因此,如果要创建其文字,我们需要对其进行转义。为此,我们需要在其前面放置\\ ,因此在其末尾表示"$0"字符串需要写为"\\"$0\\""

For more clarification about group 0 which $0 uses (quote from https://docs.oracle.com/javase/tutorial/essential/regex/groups.html ): 有关$0使用的第0组的更多说明(引自https://docs.oracle.com/javase/tutorial/essential/regex/groups.html ):

There is also a special group, group 0, which always represents the entire expression. 还有一个特殊的组,组0,它始终代表整个表达式。

If the format [A_STRING,A_STRING_ARRAY_HERE] is consistent, provided that there are no commas in any of the strings, then you can use the comma as a delimiter and then add the double quotes accordingly. 如果格式[A_STRING,A_STRING_ARRAY_HERE]是一致的,只要任何字符串中都没有逗号,则可以使用逗号作为分隔符,然后相应地添加双引号。 For example: 例如:

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, "\",\"") + "\"]]";
}

Now if you call format() with the string "[Harry,[harry potter,harry and david]]" , it would return the result you want. 现在,如果您使用字符串"[Harry,[harry potter,harry and david]]"调用format() ,它将返回您想要的结果。 Not that I used the StringUtils class from Apache Commons Lang library to join the String arrays back together with a delimiter. 并不是说我使用Apache Commons Lang库中的StringUtils类将String数组与分隔符连在一起。 You can do the same with your own custom functions. 您可以使用自己的自定义功能执行相同的操作。

This peace of program works (you can optimize it): 程序的这种平静效果(您可以对其进行优化):

//...
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM