2015-12-19 20 views
2

我正在使用Jackson準備插入ElasticSearch的JSON對象(這裏的ES有點不相關)。物體看起來像:覆蓋Jackson串行器的默認行爲

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}" 
} 

有沒有辦法做到這一點,而無需編寫自定義的串行器/解串器?

回答

2

您可以簡單地添加一個'getter'方法,它可以將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=="} 
+0

啊,本來應該公然明顯。我假設這對於setter來說是相同的(將它從JSON強制轉換爲POJO)。感謝你的回答! – Redmumba