gpt4 book ai didi

json - Json Response Spring boot 中的继承

转载 作者:行者123 更新时间:2023-12-04 10:31:57 24 4
gpt4 key购买 nike

我有两个类(class),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 忽略?

最佳答案

你创建新类(class)

public class Views {
public static class Public {
}

public static class Internal extends Public {
}
}

一类
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;
}

}

Controller
 @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));
}

关于json - Json Response Spring boot 中的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60377968/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com