Home > database >  How getting all properties (Parent and child class) in spring boot
How getting all properties (Parent and child class) in spring boot

Time:04-19

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"}] }

CodePudding user response:

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
} 

CodePudding user response:

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  '\''  
               
                '}';
    }
  • Related