dark lord
dark lord

Reputation: 33

How to access a JSON object of nested structure sent by Angular to Spring boot backend?

Suppose I have a post http request from angular having a folllowing JSON structure :

   {
       "abc":{
               "pqr":2,
               "lmn":5,
               "xyz":89
             },
       "def":[a,b,c,d],
       "klm":{
               //object attributes
             }
   }

which gets sent as a post request from angular HttpClient.

Now in spring boot Controller I am accepting it using a Hashmap of

@PostMapping("/createXyzFunctionality")
    public void createXyzFunctionality(@RequestBody Map<String, Object> json)
    {
      for (Map.Entry<String, Object> entry : json.entrySet())
      {
        //Using entry.getKey() and entry.getValue() I can access the attributes 
        //"abc","def","klm" as string but I want to access as class objects
        .....
      }
    }

Now, I have a model class for "abc" but isn't exactly the instance of my class, so when I do

CustomClass val = (CustomClass) entry.getValue();

I got ClassCastException, Help me access the attributes of the Objects in hashmap without changing the models in spring boot.

CustomClass{
      private Integer pqr,lmn,xyz;
      private String extraVariable;
      //getters setters
}

I want pqr,lmn,xyz to get values from "abc".

Upvotes: 1

Views: 729

Answers (1)

htshame
htshame

Reputation: 7330

Instead of @RequestBody Map<String, Object> json you should expect an object of the class in RequestBody.

So create a set of DTOs:

public class BodyClass {
    private Abc abc;
    private List<String> def;
    private Klm klm;
    //getters & setters
}
public class Abc {
    private Integer pqr;
    private Integer lmn;
    private Integer xyz;
}
public class Klm {
    //some parameters, getters & setters
}

And accept @RequestBody BodyClass bodyClass, e.g.:

@PostMapping("/createXyzFunctionality")
public void createXyzFunctionality(@RequestBody BodyClass bodyClass) {
    //your logic here
}

bodyClass will contain all the attributes of the JSON you're sending.

Upvotes: 4

Related Questions