Is there a way to automatically escape quotes in Java String using Gson
See original GitHub issueThis is my sample code: ` class SampleObject { String field; public SampleObject() { field = “Great ‘news’”; } public String getField() { return field; } }
private static class EscapeStringSerializer implements JsonSerializer<String> { @Override public JsonElement serialize(String s, Type type, JsonSerializationContext jsonSerializationContext) { return new JsonPrimitive(escapeSpecialChar(s)); }
public static String escapeSpecialChar(String string) {
String escapes[][] = new String[][]{
{"\'", "\\'"}
};
for (String[] esc : escapes) {
string = string.replace(esc[0], esc[1]);
}
return string;
}
}
GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(String.class, new EscapeStringSerializer()); builder.disableHtmlEscaping(); Gson customGson2 = builder.create();
String json = customGson2.toJson(sampleObject); `
I get two escape chars before the quotes instead of one. This is causing issues with serializing and deserializing the data. The Output is: {“field”:“Great \‘news\’”} instead of {“field”:“Great 'news'”} Any pointers will be greatly appreciated. Thanks
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:6
Top GitHub Comments
Are you passing the data as command line argument when starting the child process? Maybe you should then rather perform escaping on the JSON result. Also in case you are on Windows, maybe the (unfortunately not well documented) System property
jdk.lang.Process.allowAmbiguousCommands
can help. It escapes the arguments to prevent Windows from splitting or merging them. Though in general you should avoid passing it as command line argument, and if possible create a temporary file or similar to transfer the data.Looks like this has been answered, so this issue can probably be closed.