简体   繁体   中英

Converting Request body to DTO with different fields structure in Spring Web app

Spring Web works perfectly in scenarios when rest controller takes a custom object, entity or dto, as parameter of handler method. You just need to annotate it with @RequestBody annotation. But how can I handle cases when the object has different field names or structure? Ie for request json like {"name":"FirstName", "address" : { "city" : "Rome" }}

to 'flattened' structure like class Person { private String name; private String city; } class Person { private String name; private String city; }

Is it possible to create a custom converter like HttpConverter, but for specific controller handler method only?

I think the easies way is to make a DTO matching the structure of the incomming json so Spring can map the json to this DTO. Then you can map this DTO to your Person class in your controller.

If your mapping is simple it is easiest to just write the mapping yourself. If not you can use a mapping tool like https://github.com/mapstruct/mapstruct or http://modelmapper.org/ .

Please let me know if this is usefull.

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