I got a string like below:
{
"test": [
"",
"abc",
"IF(Var218 = "charlie") AND (Var85 ≤ 0) AND (Var207 = \"some value\"; \"du\") THEN Appetency = 1 ",
"",
""""
]
}
The string will be parsed as a JSON object, now the question is how should I escape some of the double quotes in the string in Java effectively?
The string above is just one example, and please notice not all double quotes in the string should be escaped, only double quotes such as in "charlie" and """" should be escaped, otherwise json parser will not parse the string correctly. Expected result should be like:
{
"test": [
"",
"abc",
"IF(Var218 = \"charlie\") AND (Var85 ≤ 0) AND (Var207 = \"some value\"; \"du\") THEN Appetency = 1 ",
"",
"\"\""
]
}
Thanks.
I'm using the Gson library for this. But it looks like this is what you are asking for.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
...
public void stuff()
{
List<String> data = new ArrayList<String>();
data.add("");
data.add("abc");
data.add("IF(Var218 = \"charlie\") AND (Var85 ≤ 0) AND (Var207 = \"some value\"; \"du\") THEN Appetency = 1 ");
data.add("\"\"");
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
JsonObject test = new JsonObject();
JsonElement jsonData = gson.toJsonTree(data, new TypeToken<List<String>>(){}.getType());
test.add("test", jsonData);
String json = gson.toJson(test);
System.out.println(json);
}
This will produce:
{
"test":[
"",
"abc",
"IF(Var218 = \"charlie\") AND (Var85 ≤ 0) AND (Var207 = \"some value\"; \"du\") THEN Appetency = 1 ",
"",
"\"\""
]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With