js整数范围:
var biggestInt = Number.MAX_SAFE_INTEGER;
//9007199254740991
var smallestInt = Number.MIN_SAFE_INTEGER;
//-9007199254740991
1、问题复现
package com.example.demo.pojo;
import lombok.Builder;
import lombok.Data;
import java.io.Serializable;
/**
* @author xuzhipeng
* @date 2022/2/22
*/
@Data
@Builder
public class TestLong implements Serializable {
private static final long serialVersionUID = 550833284250857846L;
private Long amount;
private Long age;
}
package com.example.demo.controller;
import com.example.demo.pojo.TestLong;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author xuzhipeng
* @date 2022/2/22
*/
@RestController
public class TestController {
@GetMapping("/testLong")
public TestLong testLong(){
return TestLong.builder().amount(12340551560724503L).age(30L).build();
}
}
image.png
2、配置自定义Long序列化
package com.example.demo.config;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JacksonStdImpl;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
/**
* jackson long 序列化
* @author xuzhipeng
* @date 2022/2/22
*/
@JacksonStdImpl
@SuppressWarnings("serial")
public class CustomizedLongSerializer extends StdSerializer<Object> {
private static final long JS_MAX_SAFE_INTEGER = 9007199254740991L;
private static final long JS_MIN_SAFE_INTEGER = -9007199254740991L;
public final static CustomizedLongSerializer INSTANCE = new CustomizedLongSerializer();
public CustomizedLongSerializer() { super(Object.class); }
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
if(value instanceof Long){
Long val = (Long) value;
if(val <= JS_MAX_SAFE_INTEGER && val >= JS_MIN_SAFE_INTEGER){
gen.writeNumber(val);
}else{
gen.writeString(value.toString());
}
}else{
gen.writeString(value.toString());
}
}
}
package com.example.demo.config;
import com.fasterxml.jackson.databind.JsonSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
/**
* jackson配置
* @author xuzhipeng
* @date 2022/2/22
*/
@Configuration
public class JacksonConfig {
@Bean("jackson2ObjectMapperBuilderCustomizer")
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
Map<Class<?>, JsonSerializer<?>> map = new HashMap<>(2);
map.put(Long.class, CustomizedLongSerializer.INSTANCE);
map.put(Long.TYPE, CustomizedLongSerializer.INSTANCE);
return builder -> builder.serializersByType(map);
}
}
image.png
网友评论