1

I've been hitting a block while using the spring-web library (installed via Gradle, so dependencies are installed).

I know that i can use @RequestBody to input POSTed request contents and convert it into a POJO via the Jackson Unmarshaller like so:

@RequestMapping(path = "/action", method = RequestMethod.PUT)
public MyResponsePOJO post(@RequestBody MyRequestPOJO request){
    // ...

However, I want to take the POSTed contents (JSON) as a Java JSONObject.

I've tried using @RequestBody with JSONObject but I get HTTP 400 errors.

There are a few methods that come to my mind to work around this:

  1. Input the @RequestBody as a String and parse it to a JSONObject using Jackson. (This involves me manually converting the request content, which I feel Jackson or Spring should do automatically)

  2. Add a BufferedReader parameter to my function and parse the request content with Jackson. (Again, this involves manual conversion)

  3. Input the @RequestBody as a Map<String, String> (However, my request isn't entirely String-valued)

  4. Input the @RequestBody as a Map<String, Object> (This causes issues like Unchecked Casts)

  5. Second Last Resort: Create a Request POJO with a property as Map<String, Object> (This causes the same issues as 4. above)

  6. Last Resort: Create POJOs for every expected input (Quite infeasible, as there are a lot of expected inputs)

So, is there any automatic way by which I can get the @RequestBody as a JSONObject or should I just create POJOs?

Thanks all :)

Technohacker
  • 735
  • 5
  • 19
  • 1
    The simple answer would be Create POJOs... The `@RequestBody` doesn't know about JSON, XML or whatever format you decide to use. If you really want it, and tie everything to JSON only you could write your own `HttpMessageConverter` to support the `JSONObject` however I would suggest using POJOs, we live in een OO world after all. – M. Deinum Dec 13 '16 at 14:12
  • @M.Deinum i agree, but in the project i'm working on, there are a large enough amount of inputs to consider POJOs as infeasible. That's why I'm trying to find a JSONObject solution – Technohacker Dec 13 '16 at 14:15
  • 1
    So instead of strongly typed objects, you want to parse properties and strings manually. That is hardly more feasible then maintaining proper objects. But as mentioned you could, I would however strongly advice against it as you are basically ignore OO that way (imho). – M. Deinum Dec 13 '16 at 14:16
  • @M.Deinum i'll consider creating POJOs. but i'll leave the question open for answers just in case someone else needs it for an odd reason – Technohacker Dec 13 '16 at 14:39
  • 1
    The answer is already in my first comment, write your own `HttpMessageConverter` to do that. – M. Deinum Dec 13 '16 at 14:40

0 Answers0