'How getting all properties (Parent and child class) in spring boot
I'm new in spring boot
How can i do to get all properties coming from client(Postman) json in spring boot?
For exemple i have classe
Class A{
String a;
}
Classe B extens A{
String b;
}
Class C {
long id;
List<B> c=new arraylist<>();
}
In my controller
@Postmaping()
test(@Requestbody C c){
Sysout(c);// I want get all properties a and b
}
i only got the b properties not a
My json
{ "id":1, "c":[{"a":"a","b":"b"}] }
Solution 1:[1]
In your example you have Class B extending from Class A. Therefore B is more specific. If your RequestBody contains string a and string b
{
"a":"valueA",
"b":"valueB"
}
you have to change your request Body to receive Class B.
@PostMapping("/some/endpoint)
public void test(@Requestbody B b){
System.out.println(b); // contains valueA and valueB
}
Solution 2:[2]
After a hard debugging match, I just realized that I was wrong @Override the toString() method of the child class.
It was simply necessary to add super.toString() to child class
@Override
public String toString() {
return super.toString() +
"b ='" + b+ '\'' +
'}';
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GJohannes |
| Solution 2 | Samba |
