8

I'm having a controller which receives JSON Object as input. But the problem is that, the content of JSON will vary for different requests, so Im not able to map the RequestBody to a POJO.
Is there a way I can specify the input parameter as generic JSONObject without having to specify a specific POJO.
I tried @RequestBody JSONObject inputJson. But this is throwing bad request from the client side.
I'm using spring 3.2.13 and Angular as Front End.
Any help is much appreciated. Thanks.

Abdu Manas C A
  • 1,089
  • 1
  • 11
  • 19

3 Answers3

13

It will depend a little on what you're using for JSON conversion. But you probably need to accept the input as a String and generate a JSONObject.

@RequestBody String inputJson
JSONObject jsonObj = new JSONObject(inputJson);

Or process the input as a map and just use that directly. Most versions of Jackson will perform this conversion for you:

@RequestBody Map<String, Object> inputData)
 JSONObject jsonObj = new JSONObject(inputData);

In the map case you may not need the JSONObject but you can generate it if you want.

Joe W
  • 2,773
  • 15
  • 35
  • 1
    While taking Map if the value of one property is very big in decimal, then it trims and convert it to double. How to solve that ? – Raj Saraogi Apr 27 '22 at 08:57
0

Did you try to convert the JSON as a string input and convert back to JSON? Check this thread.

Srini M
  • 196
  • 3
  • 16
0

You can use JsonNode

@RequestBody JsonNode requestBody
Santhosh Nagulanchi
  • 724
  • 4
  • 12
  • 23