I'm using GSON on my Java EE server to provide some json to views. In some object, I have long text, that can contains anything (like 'What a "great" news!').
I'm supprised that by default GSON doesn't escape the double quote, so it doesn't generate a valid JSON.
Is there a good way of doing this ?
Maybe I'm not understanding your question, but I was able to get GSON to handle Strings with quotes without any settings or changes.
import com.google.gson.Gson; public class GSONTest { public String value; public static void main(String[] args) { Gson g = new Gson(); GSONTest gt = new GSONTest(); gt.value = "This is a \"test\" of quoted strings"; System.out.println("String: " + gt.value); System.out.println("JSON: " + g.toJson(gt)); } }
Output:
String: This is a "test" of quoted strings JSON: {"value":"This is a \"test\" of quoted strings"}
Maybe I don't understand what you're asking?
Try using setPrettyPrinting with DisableHtml escaping.
import com.google.gson.Gson; Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(jsonArray.toString()); System.out.println( gson.toJson(je));
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