spring rest dynamically exclude Object properties from serialization

前端 未结 1 1538
轮回少年
轮回少年 2021-01-22 04:12

i want to exclude specific properties of spring rest response body. after hours of googling around i found this: http://www.jroller.com/RickHigh/entry/filtering_json_feeds_from_

相关标签:
1条回答
  • 2021-01-22 05:03

    In my opinion Jackson View is what you need.

    You have to define three interfaces which should cover all properties:

    1. Public - all common properties.
    2. A - properties which belong to set A.
    3. B - properties which belong to set B.

    Example interfaces:

      class Views {
                static class Public { }
                static class A extends Public { }
                static class B extends Public { }
      }
    

    Assume that your POJO class looks like this:

    class TestObject {
                @JsonView(Views.A.class) String property1;
                @JsonView(Views.B.class) String property2;
                @JsonView(Views.Public.class) String property3;
      }
    

    Now, your controller should contain below methods with annotations:

    @RequestMapping("/test1")
    @JsonView(Views.B.class)
    public TestObject test1(HttpRequest request){
        return new TestObject();
    }
    
    @RequestMapping("/test2")
    @JsonView(Views.A.class)
    public TestObject test2(HttpRequest request){
        return new TestObject();
    }
    

    All of this I has created without testing. Only by reading documentation but it should work for you. I am sure that similar solution worked for me once.

    0 讨论(0)
提交回复
热议问题