简体   繁体   中英

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 PropertyEditor s.

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 Converter s or PropertyEditor s but updating my jackson mapper is not really a solution in my case.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM