0

I have a spring boot application that accepts a JSON string in the body of the Http request. I made the controller like this

   @RequestMapping(method = RequestMapping.POST, consumes = MediaType.APPLICATION_JSON_VALUE, value = "/foo")
   public void acceptPost(@RequestBody TestModel t) {
        ....
   }

My JSON string is like this

    {
        "name" : "ABC",
        "age" : 20
    }

Spring Boot is able to marshal the request body into the TestModel POJO. But I am interested in doing the following

    @RequestMapping(method = RequestMapping.POST, consumes = MediaType.APPLICATION_JSON_VALUE, value = "/foo")
    public void acceptPost(String name, Integer age) {
        ....
    }

The name and age comes in as arguments without there being an intermediate object to hold the JSON string as it was passed.

Is there any annotation that can be used or a way to override the existing interfaces or annotations in Spring Boot to help me get what I want?

thisisshantzz
  • 878
  • 2
  • 10
  • 26

3 Answers3

1

The way you are doing is correct. This is the advisable way to do, actually and type safe way too. And you can use @PostMapping annotation(which also supports consumes property) instead of @RequestMapping

the_tech_maddy
  • 473
  • 1
  • 5
  • 16
1

I agree with everyone but still if you don’t want to create a pojo class, Get it as a JSON string @RequestBody String json.

Later use ObjecMapper to parse it as a Map then use the key to get the value. This is not required but this is another way of implementing it.

0

No, if it would have been normal query/path params or request body, then this kind of mapping was possible.

JSON is not 'universal' HTTP transfer object, hence no framework would ideally support String-within-a-JSON to String and Integer-within-a-JSON to Integer kind of out-of-the-box mapping.

Either you could have a class to get the deserialized JSON object OR you yourself could play around with query/path params or simply the request body.

gargkshitiz
  • 1,950
  • 13
  • 17