scyllaEo
V2EX  ›  Java

如何在嵌套对象里使用 @JsonView

  •  
  •   scyllaEo · Jul 18, 2019 · 4103 views
    This topic created in 2500 days ago, the information mentioned may be changed or developed.

    使用 @JsonView 可以非常简单的创建多个 view 根据不同场景使用,屏蔽掉指定的字段。但是如果是嵌套对象里就发挥不了效果,反而会返回空。 如

    class A {
     String field1; 
    
     String field2; 
    
     Collection< B> bEntities; 
    } 
     
    class B{
     @JsonView
     public interface SimpleB{/**简单 B 对象信息*/};
    
     @JsonView ( SimpleB.class )
     String field3; 
     @JsonView ( SimpleB.class )
     String field4; 
    } 
    

    上述例子,若向前端返回 A 格式在 controller 方法上指定 B 的 JsonView,则会返回空。

    @GetMapping
    @JsonView(B.SimpleB.class)
    public A getA(){
    	A a = service.getA();
        return a;
    }
    

    虽然可以使用 JsonSerializer 自己去实现 A 对象的序列化,但是这只能针对单个对象。 并且只能支持对象的一层嵌套。

    所以,有没有什么比较好的方法实现。。。。

    2 replies    2019-10-14 15:14:17 +08:00
    Jrue0011
        1
    Jrue0011  
       Jul 18, 2019
    既然是嵌套,感觉也应该要在 A.bEntities 这个属性上加 @JsonView(SimpleB.class)?
    Wmerake
        2
    Wmerake  
       Oct 14, 2019
    你好 请问你这个问题最后怎么解决的呢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2788 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 12:59 · PVG 20:59 · LAX 05:59 · JFK 08:59
    ♥ Do have faith in what you're doing.