2

I have a REST controller with a POST mapping. The request body is of type SomeBean and is optional. Currently, an empty JSON object ("{}") is deserialized to a SomeBean instead of null.
What do I need to do so that empty JSON objects are deserialized as null?

Is there a solution with annotations?

public class SomeBean implements Serializable {
  private static final long serialVersionUID = 1L;
  private String prop1;
 
  // getter and setter
  // ..
}
@RestController
@Requestmapping(path = "/service")
public class ServiceRestController {

 @PostMapping
  public Map<String, Serializable> initSession(
      @RequestBody(required = false)
      SomeBean body) {
    // ....
  }

Example curl call:

curl -XPOST -H "Content-type: application/json" -d '{}' 'http://localhost:8080/service'

WhiteCherry
  • 127
  • 9
  • can you clarify what exactly you mean by empty JSON object. what is the request that is being sent? – eis Mar 22 '21 at 10:40
  • I added an example. I mean an empty JSON object like `"{}"` – WhiteCherry Mar 22 '21 at 10:44
  • 3
    Does this answer your question? [How to tell Jackson to ignore empty object during deserialization?](https://stackoverflow.com/questions/40366524/how-to-tell-jackson-to-ignore-empty-object-during-deserialization) – Krisz Mar 22 '21 at 10:47
  • I thought there was an elegant solution for this using annotations. – WhiteCherry Mar 22 '21 at 10:56

0 Answers0