objectMapper中自定义类型转换

自己一些总结

日期类型转换

使用mapper.setDateFormat();来设置日期转换

1
2
@Select("select * from ${tableName}")
List<Map<String, Object>> getTableData(@Param("tableName") String tableName);

1
2
3
4
5
6
7
8
9
10
List<Map<String, Object>> tableDatas = tableDataMapper.getTableData("user");
for (Map<String, Object> tableData: tableDatas) {
ObjectMapper mapper = new ObjectMapper();
String data = mapper.writeValueAsString(tableData);
System.out.println(data);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));
data = mapper.writeValueAsString(tableData);
System.out.println(data);
System.out.println("=============");
}

对于byte的处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static ObjectMapper getObjectMapperForUplink() {
ObjectMapper mapper = new ObjectMapper();
// mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
// 处理字节
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(byte[].class, getByteSerialize());
mapper.registerModule(simpleModule);
// 处理日期
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));
return mapper;
}
private static JsonSerializer<byte[]> getByteSerialize() {
return new JsonSerializer<byte[]>() {
@Override
public void serialize(byte[] value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
gen.writeString(""); // 此处可实现字节转成字符串。如压缩等
}
};
}

参考

jackson中自定义处理序列化和反序列化 http://jackyrong.iteye.com/blog/2005323

文章目录
  1. 1. 日期类型转换
  2. 2. 对于byte的处理
  3. 3. 参考
|