登录
首页 >  文章 >  java教程

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

时间:2024-12-12 10:58:09 139浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《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 客户端的编码器:

@springbootapplication
public 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;

@RestController
public 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?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>