tzortzik
tzortzik

Reputation: 5133

spring 4 controller @RequestBody parameter

I have the following situation

public class MyCustomForm {
  private MyCustomType a;
  private MyCustomType b;
}

@RestController
public class AController {
  @RequestMapping(...)
  public void myMethod(@RequestBody MyCustomForm form){
    ...
  }
}

I want to send in a POST request the necessary data to fill the form. The problem is that MyCustomType is a complex data type and cannot be deserialized from JSON.

The first thing I tried was to write a PropertyEditor so that Spring will know how the make the deserialization from a string. This solution works if I use anything else beside @RequestBody (it works with @PathVariable for example).

I made some research and the reason why @RequestBody is not working is because this annotation generates a proxy which uses its own deserialization rules. Those rules do not interfere with custom PropertyEditors.

The next thing I tried was to use a custom Converter. This solution still didn't solved the issue.

Any other ideas?

I understood that the newest version of jackson (version 2) will know about the custom Converters or PropertyEditors but updating my jackson mapper is not really a solution in my case.

Upvotes: 1

Views: 539

Answers (1)

TheKojuEffect
TheKojuEffect

Reputation: 21081

You can use @JsonDeserialize for your MyCustomType classes like

public class MyCustomForm {
  @JsonDeserialize(using = MyCustomTypeDeserializer.class)
  private MyCustomType a;
  @JsonDeserialize(using = MyCustomTypeDeserializer.class)
  private MyCustomType b;
}

Some references:

https://fasterxml.github.io/jackson-databind/javadoc/2.3.0/com/fasterxml/jackson/databind/annotation/JsonDeserialize.html

http://www.davismol.net/2015/06/05/jackson-using-jsonserialize-or-jsondeserialize-annotation-to-register-a-custom-serializer-or-deserializer/

http://www.baeldung.com/jackson-custom-serialization

Upvotes: 3

Related Questions