日期类型转换
使用mapper.setDateFormat();来设置日期转换
@Select("select * from ${tableName}")
List<Map<String, Object>> getTableData(@Param("tableName") String tableName);
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的处理
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(""); // 此处可实现字节转成字符串。如压缩等
}
};
}
demo
public static ObjectMapper getObjectMapper() {
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);
return mapper;
}
/**
* 对象转为json
* @param obj
* @return
* @throws JsonProcessingException
*/
public static String object2Json(final Object obj) throws JsonProcessingException {
ObjectMapper objectMapper = getObjectMapper();
return objectMapper.writeValueAsString(obj);
}
/**
* json转为对象
* @param json
* @param clazz
* @param <T>
* @return
* @throws IOException
*/
public static <T> T json2Object(final String json, final Class<T> clazz) throws IOException {
ObjectMapper objectMapper = getObjectMapper();
return objectMapper.readValue(json, clazz);
}
属性
我们可以使用注解@JsonProperty(value="")来指定
@JsonIgnore
来忽略字段。
参考
jackson中自定义处理序列化和反序列化 http://jackyrong.iteye.com/blog/2005323