Json Response Spring boot 中的继承

Posted

技术标签:

【中文标题】Json Response Spring boot 中的继承【英文标题】:Inheritance in Json Response Spring boot 【发布时间】:2020-06-08 04:54:05 【问题描述】:

我有两个班级,A 和 B:

class A
    private int numberOne;
    private int numberTwo;
    public int getNumberOne() 
        return numberOne;
    
    public void setNumberOne(int numberOne) 
        this.numberOne = numberOne;
    
    public int getNumberTwo() 
        return numberTwo;
    
    public void setNumberTwo(int numberTwo) 
        this.numberTwo = numberTwo;
    
    

    class B extends A 

    private int numberThree;
    public int getNumberThree() 
        return numberThree;
    
    public void setNumberThree(int numberThree) 
        this.numberThree = numberThree;
    

我怎么能喜欢这样:

    ResponseEntity<A> someMethod()
        return new B(1,2,3);
    
json 
    
     "numberOne":"1",
     "numberTwo":"2"
    

    ResponseEntity<B> someMethod()
        return new B(1,2,3);
    
json 
    
     "numberOne":"1",
     "numberTwo":"2",
     "numberThree":"3"
     

如何在我想要的 Spring Boot 中使用 JSON 忽略?

【问题讨论】:

【参考方案1】:

你创建了新的类

public class Views 
public static class Public 


public static class Internal extends Public 
 

A.类

public class A 

public A(int numberOne, int numberTwo) 
    this.numberOne = numberOne;
    this.numberTwo = numberTwo;


@JsonView(Views.Public.class)
private int numberOne;
@JsonView(Views.Public.class)
private int numberTwo;

public int getNumberOne() 
    return numberOne;


public void setNumberOne(int numberOne) 
    this.numberOne = numberOne;


public int getNumberTwo() 
    return numberTwo;


public void setNumberTwo(int numberTwo) 
    this.numberTwo = numberTwo;

B.类

public class B extends A

@JsonView(Views.Internal.class)
private int numberThree;

public B(int numberOne, int numberTwo) 
    super(numberOne, numberTwo);


public B(int numberOne, int numberTwo, int numberThree) 
    super(numberOne, numberTwo);
    this.numberThree = numberThree;


public int getNumberThree() 
    return numberThree;


public void setNumberThree(int numberThree) 
    this.numberThree = numberThree;

控制器

 @GetMapping("/a-method")
@JsonView(Views.Public.class)
public ResponseEntity<A> getA()
    return ResponseEntity.ok(new B(1,2,3));


@GetMapping("/b-method")
@JsonView(Views.Internal.class)
public ResponseEntity<B> getB()
    return ResponseEntity.ok(new B(1,2,3));

【讨论】:

谢谢兄弟,按照你的例子我用这个:@JsonView(A.class)@JsonView(B.class)

以上是关于Json Response Spring boot 中的继承的主要内容,如果未能解决你的问题,请参考以下文章

Eclipse新建Spring boot提示IOException: Server returned HTTP response code: 403

Spring Boot gzip 压缩响应的大小小于配置的 min-response-size

Spring Boot rest apis 和 Response statuses 常用实践

spring boot Could not connect to SMTP host: smtp.xxx.com, port: 465, response: -1

Spring - Oauth:如何用 JSON-Response 替换 HTML 身份验证失败页面

Spring Boot实战之Filter实现简单的Http Basic认证