Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape double quotes in a string for json parser in Java

Tags:

java

json

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.

like image 468
Bruce Li Avatar asked Mar 03 '26 07:03

Bruce Li


1 Answers

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 &le; 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 &le; 0) AND (Var207 = \"some value\"; \"du\") THEN Appetency = 1 ",
    "",
    "\"\""
  ]
}
like image 101
Nick Allen Avatar answered Mar 05 '26 21:03

Nick Allen