3
按照JSON規範,字符串\中的\必須被轉義(即\\),否則其爲invalid JSON。 Gson假設「\ apple」等於「apple」而不引發異常。爲什麼呢?爲什麼Gson解析無效的Json字符串?
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'。它有什麼特別之處?
這是我自己的提示:https://www.securecoding.cert.org/confluence/display/java /IDS55-J.+Understand+how+escape+characters+are+interpreted+when+strings+are+loaded – Nilesh