在@RequestBody中使用spring转换器 [英] Using spring converter in @RequestBody

查看:178
本文介绍了在@RequestBody中使用spring转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以强制执行Converter(org.springframework.core.convert.converter.Converter)来完成json对象映射?

Is it possible to enforce Converter ( org.springframework.core.convert.converter.Converter) to finish json object mapping?

Json代码示例:

{
 "name": "somename",
 "customObject": id
}

其中somename - string,id - 整数值

where somename - string, id - integer value

映射到:

@Getter
@Setter
@NoArgConstructor
public class ParentObject{
    private String name;
    private CustomObject customObject; 
}

转换器代码示例:

@Component
public class CustomObjectConverter implements Converter<String, CustomObject>{

    @Autowired
    private CustomObjectService customObjectService;

    @Override
    public CustomObject convert(String arg0) {
        Long id = Long.parseLong(arg0);
        return customObjectService.findById(id);
    }   
}

我想要实现的是将json映射到将自动从db嵌套对象中获取的对象。

What I want to achieve is to map that json to the object which will have automatically fetched from db nested object.

推荐答案

您应该实现自己的 JacksonCustomMapper ,通过扩展 JsonMapper 然后将其注册到 HttpMessageConverters 的集合中。但是,我不建议污染默认转换,你可以传入 @RequestBody 一个不完整的json,杰克逊会将它解析为你的对象,这就足够了在你的json对象中传递错误的键...这里有一个例子(数千个): http://magicmonster.com/kb/prg/java/spring/webmvc/jackson_custom.html 。享受它: - )

You should implement your own JacksonCustomMapper, by extending JsonMapper and then registering it into the set of HttpMessageConverters. But, I do not recommend to pollute the default conversion, you could pass in the @RequestBody an incomplete json and Jackson will parse it to your object, it would be sufficient to not pass wrong keys in your json object... An example (among thousands) here: http://magicmonster.com/kb/prg/java/spring/webmvc/jackson_custom.html. Enjoy it :-)

这篇关于在@RequestBody中使用spring转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆