我有一个相当长的字符串,看起来像这样
{abc:\"def\", ghi:\"jkl\"}
我想将这个转换成有效的JSON字符串,例如:
{\"abc\":\"def\", \"ghi\":\"jkl\"}
我开始研究字符串对象上的replaceAll(String regex, String replacement)
方法,但我无法找到正确的正则表达式。
能有人帮我吗?
我必须假设“键”和“值”仅由“单词字符”(\w)组成,并且它们中没有空格。
这是我的程序。请同时查看内联注释:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexJson {
public static void main(String[] args) {
/*
* Note that the input string, when expressed in a Java program, need escape
* for backslash (\) and double quote ("). If you read directly
* from a file then these escapes are not needed
*/
String input = "{abc:\\\"def\\\", ghi:\\\"jkl\\\"}";
// regex for one pair of key-value pair. Eg: abc:\"edf\"
String keyValueRegex = "(?<key>\\w+):(?<value>\\\\\\\"\\w+\\\\\\\")";
// regex for a list of key-value pair, separated by a comma (,) and a space ( )
String pairsRegex = "(?<pairs>(,*\\s*"+keyValueRegex+")+)";
// regex include the open and closing braces ({})
String regex = "\\{"+pairsRegex+"\\}";
StringBuilder sb = new StringBuilder();
sb.append("{");
Pattern p1 = Pattern.compile(regex);
Matcher m1 = p1.matcher(input);
while (m1.find()) {
String pairs = m1.group("pairs");
Pattern p2 = Pattern.compile(keyValueRegex);
Matcher m2 = p2.matcher(pairs);
String comma = ""; // first time special
while (m2.find()) {
String key = m2.group("key");
String value = m2.group("value");
sb.append(String.format(comma + "\\\"%s\\\":%s", key, value));
comma = ", "; // second time and onwards
}
}
sb.append("}");
System.out.println("input is: " + input);
System.out.println(sb.toString());
}
}
这个程序的输出结果是:
input is: {abc:\"def\", ghi:\"jkl\"}
{\"abc\":\"def\", \"ghi\":\"jkl\"}
setLenient()
方法。然后将其重新写回为有效的JSON格式。 - Andreas:
进行替换,但如果值字符串中有冒号,则可能会失败。其他可能会使您失败的事情是在其中一个值内部存在转义引号。可能可以想出一个处理所有内容的复杂正则表达式,但在这种情况下,最好编写自己的词法分析器来处理输入中的标记(如{
、:
、,
、标识符、字符串文字)并从中工作。过于复杂的正则表达式难以阅读且容易出错。 - ajb