亲宝软件园·资讯

展开

SpringBoot返回对象将Long类型转换为String

Garfield_cat_cat 人气:0

SpringBoot返回对象将Long类型转换为String

1.自定义ObjectMapper

/**
 * 返回Long转换为String
 * @author Jingly
 */
public class JacksonMapper extends ObjectMapper {
  public JacksonMapper() {
    super();
    this.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
    this.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
    this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    this.setSerializationInclusion(Include.NON_NULL);
    SimpleModule simpleModule = new SimpleModule();
    simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
    simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
    simpleModule.addSerializer(long.class, ToStringSerializer.instance);
    registerModule(simpleModule);
  }
}

2.把MappingJackson2HttpMessageConverter

设置给HttpMessageConverter

/**
 * @author Jingly
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
  @Autowired
  private HttpMessageConverters httpMessageConverters;
  /**
   * MappingJackson2HttpMessageConverter 实现了HttpMessageConverter 接口,
   * httpMessageConverters.getConverters() 返回的对象里包含了MappingJackson2HttpMessageConverter
   * @return
   */
  @Bean
  public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
    return new MappingJackson2HttpMessageConverter(new JacksonMapper());
  }
  @Override
  public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.addAll(httpMessageConverters.getConverters());
  }
}

3.定义返回的VO类

@Data
public class TestVO {
  private Long id;
}

4.返回的Long类型id为String类型

{
    "id": "123456"
}

Long类型转换为String类型的方法及区别

1、Long.ValueOf ("String") 返回 Long 包装类型数据

2、Long.parseLong ("String") 返回 long 基本数据类型

注意事项

1、字符串内不能包含除数字之外的字符,不然会报错,java.lang.NumberFormatException

2、字符串长度要限制,不然也会报错。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论