fastjson过滤属性
发布时间:2020-12-16 19:15:09 所属栏目:百科 来源:网络整理
导读://实现PropertyFilter中的apply方法 public class ComplexPropertyPreFilter implements PropertyFilter {private MapClass?,SetString includeMap = new HashMapClass?,SetString();//@Overridepublic boolean apply(Object source,String name,Object valu
//实现PropertyFilter中的apply方法 public class ComplexPropertyPreFilter implements PropertyFilter { private Map<Class<?>,Set<String>> includeMap = new HashMap<Class<?>,Set<String>>(); //@Override public boolean apply(Object source,String name,Object value) { for(Entry<Class<?>,Set<String>> entry : includeMap.entrySet()) { Class<?> class1 = entry.getKey(); if(source.getClass() == class1){ Set<String> fields = entry.getValue(); for(String field : fields) { if(field.equals(name)){ return false; } } } } return true; } public ComplexPropertyPreFilter(Map<Class<?>,Set<String>> includeMap){ this.includeMap = includeMap; } }
测试类: class Wheel{ String name; int size; String color; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public Wheel() { super(); this.color="black"; this.name="miqilin"; this.size = 17; } } class Sofa{ String color; int count; String texture; public String getColor() { return color; } public void setColor(String color) { this.color = color; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public String getTexture() { return texture; } public void setTexture(String texture) { this.texture = texture; } public Sofa() { super(); this.color = "white"; this.count = 4; this.texture = "fur"; } } class Car { private Wheel wheel; private Sofa sofa; public Wheel getWheel() { return wheel; } public void setWheel(Wheel wheel) { this.wheel = wheel; } public Sofa getSofa() { return sofa; } public void setSofa(Sofa sofa) { this.sofa = sofa; } public Car() { super(); this.wheel = new Wheel(); this.sofa = new Sofa(); } } public class Test { public static void main(String args[]){ Map<String,Car> map = new HashMap<String,Car>(); map.put("car1",new Car()); map.put("car2",new Car()); //需要过滤的类 + 属性 Map<Class<?>,Set<String>>(); Set<String> set = new HashSet<String>(); set.add("color"); includeMap.put(Wheel.class,set); set = new HashSet<String>(); set.add("texture"); includeMap.put(Sofa.class,set); ComplexPropertyPreFilter cfilter = new ComplexPropertyPreFilter(includeMap); SerializeWriter sw = new SerializeWriter(); JSONSerializer serializer = new JSONSerializer(sw); serializer.getPropertyFilters().add(cfilter); serializer.write(map); System.out.println(sw.toString()); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |