[英]Inheritance in Json Response Spring boot
I have two classes, A and B:我有两个班级,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;
}
}
How do I can like this:我怎么能喜欢这个:
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"
}
How can I use JSON ignoring in Spring Boot which I want?如何在我想要的 Spring Boot 中使用 JSON 忽略?
You create new class你创建新班级
public class Views {
public static class Public {
}
public static class Internal extends Public {
}
}
A.class一类
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.class 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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.