跟前端联调时,发现一个问题,返回给前端的字段id long型 后端postman 得到的是9433916916430849,但前端取到的是9433916916430848
这就很诡异!为啥前端得到的值会自动减一!
具体为啥会减一也没有搞清楚,但找到了解决办法~
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.TYPE, LongToStringSerializer.INSTANCE);
simpleModule.addSerializer(Long.class, LongToStringSerializer.INSTANCE);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(simpleModule);
// JSON里面包含了实体没有的字段导致反序列化失败
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
converters.clear();
converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
super.configureMessageConverters(converters);
}
}
import java.io.IOException;
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;
@JacksonStdImpl
public class LongToStringSerializer extends StdSerializer<Long> {
public static final LongToStringSerializer INSTANCE = new LongToStringSerializer();
public static final int MIN_CONVER_LENGTH = 14;
public LongToStringSerializer() {
super(Long.class);
}
@Override
public boolean isEmpty(SerializerProvider provider, Long value) {
if (value == null) {
return true;
}
return false;
}
@Override
public void serialize(Long aLong, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException {
int length = aLong.toString().length();
if (length > MIN_CONVER_LENGTH) {
jsonGenerator.writeString(aLong.toString());
} else {
jsonGenerator.writeNumber(aLong);
}
}
}
网友评论