fastjson过滤属性,重点在于PropertyFilter 这个东西(应用场景,hibernate懒加载过滤不要的属性)

前端之家收集整理的这篇文章主要介绍了fastjson过滤属性,重点在于PropertyFilter 这个东西(应用场景,hibernate懒加载过滤不要的属性)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. //实现PropertyFilter中的apply方法
[java] view plain copy

    publicclassComplexPropertyPreFilterimplementsPropertyFilter{
  1. privateMap<Class<?>,Set<String>>includeMap=newHashMap<Class<?>,Set<String>>();
  2. //@Override
  3. booleanapply(Objectsource,Stringname,Objectvalue){
  4. for(Entry<Class<?>,Set<String>>entry:includeMap.entrySet()){
  5. Class<?>class1=entry.getKey();
  6. if(source.getClass()==class1){
  7. Set<String>fields=entry.getValue();
  8. for(Stringfield:fields){
  9. if(field.equals(name)){
  10. returnfalse;
  11. }
  12. }
  13. true;
  14. publicComplexPropertyPreFilter(Map<Class<?>,Set<String>>includeMap){
  15. this.includeMap=includeMap;
  16. }


测试类:

copy
    classWheel{
  1. Stringname;
  2. intsize;
  3. Stringcolor;
  4. publicStringgetName(){
  5. returnname;
  6. voidsetName(Stringname){
  7. this.name=name;
  8. intgetSize(){
  9. returnsize;
  10. voidsetSize(intsize){
  11. this.size=size;
  12. publicStringgetColor(){
  13. returncolor;
  14. voidsetColor(Stringcolor){
  15. this.color=color;
  16. publicWheel(){
  17. super();
  18. this.color="black";
  19. this.name="miqilin";
  20. this.size=17;
  21. classSofa{
  22. Stringcolor;
  23. intcount;
  24. Stringtexture;
  25. publicStringgetColor(){
  26. returncolor;
  27. voidsetColor(Stringcolor){
  28. this.color=color;
  29. intgetCount(){
  30. returncount;
  31. voidsetCount(intcount){
  32. this.count=count;
  33. publicStringgetTexture(){
  34. returntexture;
  35. voidsetTexture(Stringtexture){
  36. this.texture=texture;
  37. publicSofa(){
  38. super();
  39. this.color="white";
  40. this.count=4;
  41. this.texture="fur";
  42. classCar{
  43. privateWheelwheel;
  44. privateSofasofa;
  45. publicWheelgetWheel(){
  46. returnwheel;
  47. voidsetWheel(Wheelwheel){
  48. this.wheel=wheel;
  49. publicSofagetSofa(){
  50. returnsofa;
  51. voidsetSofa(Sofasofa){
  52. this.sofa=sofa;
  53. publicCar(){
  54. this.wheel=newWheel();
  55. this.sofa=newSofa();
  56. classTest{
  57. staticvoidmain(Stringargs[]){
  58. Map<String,Car>map=newHashMap<String,Car>();
  59. map.put("car1",newCar());
  60. map.put("car2",153); font-weight:bold; background-color:inherit">newCar());
  61. //需要过滤的类+属性
  62. Map<Class<?>,Set<String>>includeMap= Set<String>set=newHashSet<String>();
  63. set.add("color");
  64. includeMap.put(Wheel.class,set);
  65. set=newHashSet<String>();
  66. set.add("texture");
  67. includeMap.put(Sofa. ComplexPropertyPreFiltercfilter=newComplexPropertyPreFilter(includeMap);
  68. SerializeWritersw=newSerializeWriter();
  69. JSONSerializerserializer=newJSONSerializer(sw);
  70. serializer.getPropertyFilters().add(cfilter);
  71. serializer.write(map);
  72. System.out.println(sw.toString());
  73. }
原文链接:https://www.f2er.com/json/289340.html

猜你在找的Json相关文章