Spring RESTful API中如何避免Long类型序列化为String?

spring restful api中如何避免long类型序列化为string?

如何避免 spring restful api 中 long 类型序列化为 string

在 spring 应用中,将 long 类型数据序列化为 json 字符串时,如果希望在 restful api 和内部服务之间采用不同的序列化机制,这里提供一种方法:

针对 restful api:

配置 @restcontroller 类的 produces 属性:

@restcontroller@requestmapping(value = "/api", produces = "application/json")public class myrestcontroller {

登录后复制

在 application.properties 中配置消息转换器:

spring.jackson.serialization.write_dates_as_timestamps=false

登录后复制

针对内部服务:

配置 feign 客户端的编码器:

@springbootapplicationpublic class myapplication {    public static void main(string[] args) {        springapplication.run(myapplication.class, args);    }    @bean    public encoder feignencoder() {        return new springencoder(new mappingjackson2httpmessageconverter(                new jackson2objectmapperbuilder().build()        ));    }}

登录后复制

java 对象的映射器:

import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import java.math.BigInteger;@RestControllerpublic class MyController {    // 确保注入的不是容器里的 ObjectMapper    @Autowired private ObjectMapper objectMapper;    @GetMapping("/demo")    public String demo() {        return objectMapper.writeValueAsString(BigInteger.valueOf(1L));    }}

登录后复制

通过上述配置,restful api 将long 值序列化为字符串,而内部服务不会转换。

以上就是Spring RESTful API中如何避免Long类型序列化为String?的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2607975.html

(0)
上一篇 2025年3月6日 20:33:37
下一篇 2025年2月24日 09:14:49

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论