155

I noticed that Gson converts the string "<" into an unicode escape sequence in JSON output. Can you avoid this somehow, or do characters like "<" and ">" always have to be escaped in JSON?

Consider this example which prints {"s":"\u003c"}; I'd want simply {"s":"<"}.

public static void main(String[] args) {
    Gson gson = new GsonBuilder().create();
    System.out.println(gson.toJson(new Foo()));  
}

static class Foo {
    String s = "<";
}

Context: the piece of JSON I'm creating has nothing to do with HTML pages or even JavaScript; it's just used to pass certain structured information to another piece of software (embedded in a device, written in C).

Jonik
  • 80,077
  • 70
  • 264
  • 372
  • 4
    Does GSON default to doing that? Whoa. That is rather strange default setting, although perfectly legal thing to do from JSON spec perspective. – StaxMan Nov 10 '10 at 19:26
  • 4
    Yeah, it was surprising to me too. Luckily the [remedy](http://stackoverflow.com/questions/4147012/can-you-avoid-gson-converting-and-into-unicode-escape-sequences/4147245#4147245) is easy once you know where to look. :) Otherwise, after one day's experience with it, I find Gson a really clean, nice library, with a great [user guide](http://sites.google.com/site/gson/gson-user-guide) too! – Jonik Nov 10 '10 at 19:44
  • 7
    This also happens to the "=" character, which turns into "\u003d". – Russell Silva May 04 '11 at 21:08

2 Answers2

306

You need to disable HTML escaping.

Gson gson = new GsonBuilder().disableHtmlEscaping().create();
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 16
    I wonder why it's on by default. JSON has nothing to do with HTML. The [spec](http://www.json.org/) states only `"` and `\\` need to be escaped. – Mark Jeronimus Feb 16 '17 at 10:41
  • Guys, thats not worked for me. i am using ''com.squareup.retrofit2:retrofit:2.3.0'' && ''com.squareup.retrofit2:converter-gson:2.3.0''. Please help me. – Mr Code Apr 04 '18 at 05:06
2

the Ampasand symbol was replacing with \u0026 , by using this it got resolved.

ROOPA P D
  • 21
  • 1
  • 1
    But sometimes, for the sake of readability and compatibility with external input data, such as deserialization of objects, the control from the [data source] here may be impossible or too expensive; this time , Reasonable use of Gson's own principle mechanism and configuration may be a better choice. – Lancer.Yan Mar 04 '22 at 08:37