Search code examples
javajsongson

Can you avoid Gson converting "<" and ">" into unicode escape sequences?


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).


Solution

  • You need to disable HTML escaping.

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