为什么Gson会解析无效的Json字符串?

时间:2016-06-24 06:24:08

标签: java json gson

根据JSON规范,字符串中的\必须被转义(即\\),否则为invalid JSON。 Gson认为“\ apple”等于“apple”而不提出异常。为什么呢?

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
}
}

输出:

 In Json = \apple
 In Pojo = apple

只有第一个字符和'a'才会发生。什么特别的?

1 个答案:

答案 0 :(得分:2)

Gson默认情况下只是转义,如果此方法对您的方法不正确,只需执行以下操作:

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