Using generic JSON Object as Request Body

北城以北 提交于 2020-07-06 11:22:50

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/51151695/using-generic-json-object-as-request-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!