objectMapper中自定义类型转换

日期类型转换

使用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

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值