Nilesh
Nilesh

Reputation: 2168

Why Gson parses invalid Json string?

As per JSON spec, \ in string must be escaped (i.e, \\) otherwise its invalid JSON. Gson assumes "\apple" is equal to "apple" without raising an Exception. Why does it ?

public class MainApp {

public static void main(String[] args) {
    String str = "{\"bar\":\"\\apple\"}";
    /*
        str without escaping = 
        {
            "bar" : "\apple"
        }
    */

    Foo foo = new Gson().fromJson(str, Foo.class);
    System.out.println("In Json = " + "\\" + "apple");
    System.out.println("In Pojo = " + foo.getBar());
}

class Foo {
    private String bar;
    //Setter and getters stripped
}
}

Output:

 In Json = \apple
 In Pojo = apple

It happens only with first character and with 'a'. Whats special in it?

Upvotes: 3

Views: 1221

Answers (1)

Matteo Baldi
Matteo Baldi

Reputation: 5828

Gson simply escapes by default, if this behaviour is not correct for your method simply do:

Gson gson = new GsonBuilder().disableHtmlEscaping().create();
Foo foo = gson.fromJson(str, Foo.class);

Upvotes: 2

Related Questions