Gson - Automatic quote (") escaping?

Stéphane Piette picture Stéphane Piette · Aug 31, 2011 · Viewed 49.2k times · Source

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 ?

Answer

Todd picture Todd · Aug 31, 2011

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?