objectMapper中自定义类型转换

日期类型转换

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

@Select("select * from ${tableName}")
List> getTableData(@Param("tableName") String tableName);
List> tableDatas = tableDataMapper.getTableData("user");
for (Map 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 getByteSerialize() {
    return new JsonSerializer() {
        @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 
 * @return
 * @throws IOException
 */
public static  T json2Object(final String json, final Class clazz) throws IOException {
    ObjectMapper objectMapper = getObjectMapper();
    return objectMapper.readValue(json, clazz);
}

属性

我们可以使用注解@JsonProperty(value="")来指定

@JsonIgnore来忽略字段。

参考

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

你可能感兴趣的:(SpringBoot)