1

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".

4
  • Mapping objects to specific classes is generally a good idea. Commented Feb 21, 2020 at 7:33
  • @Carsten I assume you wanted to write "... NOT a good idea"? Commented Feb 21, 2020 at 7:45
  • @Endzeit lol no. Where on earth would you get that idea? Commented Feb 21, 2020 at 7:53
  • @Carsten I think there is a misunderstanding. I think you are talking about mapping JSON-Objects to specific classes instead of the Object class. I thought you meant casting Object to specific classes was a good idea. I doubt that casting is a good idea and should be circumvented where applicable. I agree that you should use specific classes and in general strong typing. My mistake. Commented Feb 21, 2020 at 13:34

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.