我在字符串下面,但是我想在其中添加双引号,使其看起来像json

[
{
   LastName=abc,
   FirstName=xyz,
   [email protected],
   IncludeInEmails=false
},
{
  LastName=mno,
  FirstName=pqr,
  [email protected],
  IncludeInEmails=true
}
]

我想要下面的输出。
[
    {
       "LastName"="abc",
       "FirstName"="xyz",
       "EmailAddress"="[email protected]",
       "IncludeInEmails"=false
    },
    {
      "LastName"="mno",
      "FirstName"="pqr",
      "EmailAddress"="[email protected]",
      "IncludeInEmails"=true
    }
    ]

我已经尝试过一些字符串正则表达式。但没有。谁能帮忙。
String text= jsonString.replaceAll("[^\\{\\},]+", "\"$0\"");
System.out.println(text);

谢谢

最佳答案

正则表达式的方式,类似于您尝试的方法:

    String jsonString = "[ \n" + "{ \n" + "   LastName=abc,  \n" + "   FirstName=xyz,  \n"
            + "   [email protected],  \n" + "   IncludeInEmails=false \n" + "}, \n" + "{  \n"
            + "  LastName=mno,  \n" + "  FirstName=pqr,  \n" + "  [email protected],  \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);

关于java - 我如何添加双引号看起来像json,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36493506/

10-09 04:39