1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
/**
* 全局序列化配置类
*
* @author GuoYingdong
* @date 2023/02/02
*/
@Configuration
public class JsonConfig {
/**
* 创建Jackson对象映射器
*
* @param builder Jackson对象映射器构建器
* @return ObjectMapper
*/
@Bean
public ObjectMapper getJacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
this.registerLongSerializer(objectMapper);
this.registerGeometrySerializer(objectMapper);
//反序列化的时候如果多了其他属性,不抛出异常
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//日期格式处理
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
return objectMapper;
}
/**
* 注册 Long 类型的序列化器
* @param objectMapper
*/
private void registerLongSerializer(ObjectMapper objectMapper){
//序列换成json时,将所有的long变成string.因为js中得数字类型不能包含所有的java long值,超过16位后会出现精度丢失
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, com.fasterxml.jackson.databind.ser.std.ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, com.fasterxml.jackson.databind.ser.std.ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
}
/**
* 注册 Geometry 类型的序列化器
*
* @param objectMapper
*/
private void registerGeometrySerializer(ObjectMapper objectMapper) {
SimpleModule simpleModule = new SimpleModule();
JsonSerializer<Geometry> serializer = new JsonSerializer<Geometry>() {
@Override
public void serialize(Geometry geometry, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
JtsModule.DEFAULT_MAX_DECIMALS = 14;
String geoJSON = GeoJSONWriter.toGeoJSON(geometry);
jsonGenerator.writeString(geoJSON);
}
@Override
public Class<Geometry> handledType() {
return Geometry.class;
}
};
simpleModule.addSerializer(serializer);
GenericGeometryParser genericGeometryParser = new GenericGeometryParser(geometryFactory);
simpleModule.addDeserializer(Geometry.class, new GeometryDeserializer<>(genericGeometryParser));
objectMapper.registerModule(simpleModule);
}
}
|