简体   繁体   中英

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

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.

Is there a simple way to do this, I don't want to add "" for a very single String from scratch .

Demo

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

System.out.println(text);

Output: ["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

  • [^\\\\[\\\\],] - 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" . 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\\"" .

For more clarification about group 0 which $0 uses (quote from https://docs.oracle.com/javase/tutorial/essential/regex/groups.html ):

There is also a special group, group 0, which always represents the entire expression.

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. 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. Not that I used the StringUtils class from Apache Commons Lang library to join the String arrays back together with a delimiter. 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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