我有下面的字符串,但我想在其中添加双引号看起来像json
[
{
LastName=abc,
FirstName=xyz,
EmailAddress=s@s.com,
IncludeInEmails=false
},
{
LastName=mno,
FirstName=pqr,
EmailAddress=m@m.com,
IncludeInEmails=true
}
]
我想要低于输出。
[
{
"LastName"="abc",
"FirstName"="xyz",
"EmailAddress"="s@s.com",
"IncludeInEmails"=false
},
{
"LastName"="mno",
"FirstName"="pqr",
"EmailAddress"="m@m.com",
"IncludeInEmails"=true
}
]
我试过一些字符串正则表达式。但没有得到。请任何人帮忙。
String text= jsonString.replaceAll("[^\\{\\},]+", "\"$0\"");
System.out.println(text);
感谢
答案 0 :(得分:4)
正则表达式方式,类似于您尝试过的方法:
String jsonString = "[ \n" + "{ \n" + " LastName=abc, \n" + " FirstName=xyz, \n"
+ " EmailAddress=s@s.com, \n" + " IncludeInEmails=false \n" + "}, \n" + "{ \n"
+ " LastName=mno, \n" + " FirstName=pqr, \n" + " EmailAddress=m@m.com, \n" + " Number=123, \n"
+ " IncludeInEmails=true \n" + "} \n" + "] \n";
System.out.println("Before:\n" + jsonString);
jsonString = jsonString.replaceAll("([\\w]+)[ ]*=", "\"$1\" ="); // to quote before = value
jsonString = jsonString.replaceAll("=[ ]*([\\w@\\.]+)", "= \"$1\""); // to quote after = value, add special character as needed to the exclusion list in regex
jsonString = jsonString.replaceAll("=[ ]*\"([\\d]+)\"", "= $1"); // to un-quote decimal value
jsonString = jsonString.replaceAll("\"true\"", "true"); // to un-quote boolean
jsonString = jsonString.replaceAll("\"false\"", "false"); // to un-quote boolean
System.out.println("===============================");
System.out.println("After:\n" + jsonString);
答案 1 :(得分:0)
只需使用此库http://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1
以下是您的示例代码:
JSONArray json = new JSONArray();
JSONObject key1 = new JSONObject();
key1.put("LastName", "abc");
key1.put("FirstName", "xyz");
key1.put("EmailAddress", "s@s.com");
key1.put("IncludeInEmails", false);
JSONObject key2 = new JSONObject();
key2.put("LastName", "mno");
key2.put("FirstName", "pqr");
key2.put("EmailAddress", "m@m.com");
key2.put("IncludeInEmails", true);
json.add(key1);
json.add(key2);
System.out.println(json.toString());
答案 2 :(得分:0)
由于存在许多极端情况,例如字符转义,布尔值,数字...... ......简单的正则表达式不会这样做。
您可以按换行分割输入字符串,然后单独处理每个键值对
for (String line : input.split("\\R")) {
// split by "=" and handle key and value
}
但是,你必须处理char。转义,布尔值,...(和btw,=
不是有效的JSON键值分隔符,只有:
是。
我建议使用GSON,因为它提供lenient
解析。使用Maven
,您可以使用此依赖项将其添加到项目中:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
然后,您可以使用
解析input
字符串
String output = new JsonParser()
.parse(input)
.toString();