Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson - Automatic quote (") escaping?

Tags:

java

json

gson

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 ?

like image 661
Stéphane Piette Avatar asked Aug 31 '11 14:08

Stéphane Piette


2 Answers

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?

like image 148
Todd Avatar answered Sep 22 '22 13:09

Todd


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)); 
like image 24
Ammad Avatar answered Sep 18 '22 13:09

Ammad