各類json庫對屬性過濾都支持,但使用起來不夠靈活。本文介紹的方法經過讀取原生的 json字符串實現屬性動態過濾,因此不須要依賴具體的json庫。 java
例子以下: git
String json = "{\"name\":\"mi米\",\"age\":30,\"weight\":100.1,\"Children\":[\"a\",\"b\",\"c\"],\"address\":{ \"city\":\"GuangZhou\",\"pro\":\"GuangDong\"}}"; Assert.assertEquals("{\"name\":\"mi米\",\"weight\":100.1,\"address\":{ \"city\":\"GuangZhou\" }", JsonUtils.removeProperty(json, new String[]{"name", "weight", "address.city"}, true));
String json = "{\"name\":\"mi米\",\"age\":30,\"weight\":100.1,\"Children\":[\"a\",\"b\",\"c\"],\"address\":{ \"city\":\"GuangZhou\",\"pro\":\"GuangDong\"}}"; Assert.assertEquals("{\"name\":\"mi米\",\"weight\":100.1,\"address\":{ \"city\":\"GuangZhou\" }", JsonUtils.removeProperty(json, new String[]{"age", "Children", "address.pro"}, false));
詳細代碼請參考:https://github.com/wenzuojing/json-util github