各类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