2013-12-17 32 views
21

我有一些JSON已經在秒時間戳(即Unix時間戳):如何反序列化傑克遜在幾秒鐘內的時間戳?

{"foo":"bar","timestamp":1386280997} 

問傑克遜與時間戳結果的日期時間字段中1970-01-17T01:11:25.983Z後不久,反序列化到這個對象,一時間因爲傑克遜假設它在毫秒。除了撕裂JSON並添加一些零之外,我如何讓傑克遜瞭解時間戳?

+3

有一個問題[這裏](http://stackoverflow.com/questions/5591967/jackson-date-deserialization),顯示如何實現自定義日期反序列化類 – Slicedpan

+0

感謝您的提示 - 我回答了這個問題由於解串器有點不同,我如何解決這個問題的細節來自這個問題。 –

回答

22

我寫了一個自定義的deserializer以秒爲單位處理時間戳(Groovy語法)。

class UnixTimestampDeserializer extends JsonDeserializer<DateTime> { 
    Logger logger = LoggerFactory.getLogger(UnixTimestampDeserializer.class) 

    @Override 
    DateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { 
     String timestamp = jp.getText().trim() 

     try { 
      return new DateTime(Long.valueOf(timestamp + '000')) 
     } catch (NumberFormatException e) { 
      logger.warn('Unable to deserialize timestamp: ' + timestamp, e) 
      return null 
     } 
    } 
} 

然後我註釋我的POGO使用,對於時間戳:

class TimestampThing { 
    @JsonDeserialize(using = UnixTimestampDeserializer.class) 
    DateTime timestamp 

    @JsonCreator 
    public TimestampThing(@JsonProperty('timestamp') DateTime timestamp) { 
     this.timestamp = timestamp 
    } 
} 
+0

你好,出於好奇,Java的方言是什麼?謝謝! – tuscland

+0

在普通的枯燥的java中也像魅力一樣工作。只需在您需要的任何DateTime字段上使用Annotation即可。沒有嘗試使用Java 8 Date,但應該沒有問題。謝謝 – thomi

+0

@tuscland Groovy –

10
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="s") 
public Date timestamp; 

編輯:維韋克 - 科塔裏建議

@JsonFormat(shape=JsonFormat.Shape.NUMBER, pattern="s") 
public Timestamp timestamp; 
+0

爲什麼downvote?因爲它比其他解決方案更容易? – sherpya

+1

可能是因爲它的時間戳在json中表示爲'integer'而不是'string'。 –

+1

傑克遜需要的類型轉換 – sherpya

7

一個非常類似的方法@ DrewStephens的使用Java SE TimeUnit A PI(在JDK1.5介紹),而不是簡單的字符串連接,因此是(可以說)一點點更清潔,更表現:

public class UnixTimestampDeserializer extends JsonDeserializer<Date> { 

    @Override 
    public Date deserialize(JsonParser parser, DeserializationContext context) 
      throws IOException, JsonProcessingException { 
     String unixTimestamp = parser.getText().trim(); 
     return new Date(TimeUnit.SECONDS.toMillis(Long.valueOf(unixTimestamp))); 
    } 
} 

對受影響Date場(S)指定您的自定義解串器(UnixTimestampDeserializer):

@JsonDeserialize(using = UnixTimestampDeserializer.class) 
private Date updatedAt;