覆盖Jackson序列化程序的默认行为

时间:2015-12-19 00:06:31

标签: java json elasticsearch jackson

我正在使用Jackson来准备要插入ElasticSearch的JSON对象(ES在这里有些不相关)。该对象看起来像:

class TimestampedCount {
    private Date timestamp;
    private Map<Long, Integer> counts;
}

正如预期的那样,默认行为是将counts变量转换为对象。但是,由于我在ES中存储数据的方式,我想将地图强制转换为byte[]String字段,而不必更改已定义的类型。换句话说,我希望它的存储方式与它的使用方式不同。例如,如果我将其转换为String,我会期望在最终的JSON中出现以下内容:

{
    "timestamp": 12355812312,
    "counts": "{1: 15431, 2: 15423, 3: 1314}"
}

有没有办法在不必编写自定义序列化器/解串器的情况下执行此操作?

1 个答案:

答案 0 :(得分:2)

你可以简单地添加一个“getter”&#39;将Map转换为合适格式的方法。这是一个返回字节数组的例子:

public class JacksonGetter {
    static class TimestampedCount {
        private final Date timestamp;
        private final Map<Long, Integer> counts;

        public TimestampedCount(final Date timestamp, final Map<Long, Integer> counts) {
            this.timestamp = timestamp;
            this.counts = counts;
        }

        public Date getTimestamp() { return timestamp; }

        @JsonProperty("counts")
        public byte[] getCountsAsBytes() {
            return counts.toString().getBytes();
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        final TimestampedCount timestampedCount = new TimestampedCount(
                new Date(),
                Collections.singletonMap(1L, 123));
        final ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(timestampedCount));

    }
}

输出:

{"timestamp":1450555085608,"counts":"ezE9MTIzfQ=="}