Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues with using Gson to pretty-print JSON String

Tags:

java

json

gson

Could someone please suggest why this is happening...

I’ve got some code to pretty print some JSON. To do this, I am making use out of the Gson library.

However, while thus usually works well, some characters don’t seem to be displayed properly. Here is a simple piece of code that demonstrates the problem:

//Creating the JSON object, and getting as String:
JsonObject json = new JsonObject();
JsonObject inner = new JsonObject();
inner.addProperty("value", "xpath('hello')");
json.add("root", inner);
System.out.println(json.toString());

//Trying to pretify JSON String:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser parser = new JsonParser();
JsonElement je = parser.parse(json.toString());
System.out.println(gson.toJson(je));

The output of the above code is:

{"root":{"value":"xpath('hello')"}}
{
  "root": {
    "value": "xpath(\u0027hello\u0027)"
  }
}

How could I fix the above?

like image 355
Larry Avatar asked Jun 13 '12 18:06

Larry


People also ask

What is pretty printing GSON?

By: Lokesh Gupta. Gson. Gson Basics, Pretty Print. By default, Gson prints the JSON in compact format. It means there will not be any whitespace in between field names and its value, object fields, and objects within arrays in the JSON output etc.

Is GSON fromJson thread safe?

Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it. Gson instances are Thread-safe so you can reuse them freely across multiple threads.

Is GSON deprecated?

Gson is not deprecated.

How do you print your response in JSON format in Java?

We can pretty-print a JSON using the toString(int indentFactor) method of org. json. JSONObject class, where indentFactor is the number of spaces to add to each level of indentation.


1 Answers

Use this code, to create Gson object:

Gson gs = new GsonBuilder()
    .setPrettyPrinting()
    .disableHtmlEscaping()
    .create();

The disableHtmlEscaping() method tells gson not to escape HTML characters such as <, >, &, =, and a single quote which caused you trouble: '.

Note, that this may cause trouble, if you render such unescaped JSON into a <script/> tag in HTML page without using additional <![CDATA[ ... ]]> tag.

You can see how it works, and what other chars are escaped, by looking into the code of JsonWriter class.

like image 163
npe Avatar answered Nov 01 '22 21:11

npe