Monday, 13 December 2021

Gson: Disable HTML escaping

In this post, I am going to explain how to disable HTML escaping in Gson library. By default, Gson escapes HTML characters such as <, >.

 

For example,

 

Model.java

package com.sample.app.json;

public class Model {

	private String data;

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}

}

 

JsonEscapingDemo.java

package com.sample.app.json;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonEscapingDemo {

	public static void main(String args[]) {
		Gson gson = new GsonBuilder().create();

		Model obj = new Model();
		obj.setData("Hello this is <Krishna>");

		String json = gson.toJson(obj);
		System.out.println(json);
	}

}

 

Output

{"data":"Hello this is \u003cKrishna\u003e"}

 

As you see above snippet, HTML characters < and > are escaped with unicodes \u003c, \u003e.

 

How can I disable HTML escaping?

Disable HTML escaping using disableHtmlEscaping() method.

 

Example

 

Gson gson = new GsonBuilder().disableHtmlEscaping().create();

 

JsonEscapingDemo.java

package com.sample.app.json;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonEscapingDemo {

	public static void main(String args[]) {
		Gson gson = new GsonBuilder().disableHtmlEscaping().create();

		Model obj = new Model();
		obj.setData("Hello this is <Krishna>");

		String json = gson.toJson(obj);
		System.out.println(json);
	}

}

 

Output

{"data":"Hello this is <Krishna>"}

 

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment