2017-07-19 85 views
1

我有一個舒適的問題,在休息api中使用傑克遜。 我使用傑克遜序列化有任何類型的屬性,像java.time對象:傑克遜使兩個json屬性的一個java屬性

public class DomainObject{ 
    public LocalDateTime start; 
} 

我可以用傑克遜製作這樣的事情:

{ 
    start: '2017-12-31 17:35:22' 
} 

,我可以用它來產生這樣的事情:

{ 
    start: 102394580192345 //milliseconds 
} 

但我想有兩個,在JS來workwith毫秒和字符串表示誰使用REST的API純粹機智用戶hout js-front。 (主要是我,用於調試)

所以有什麼辦法,讓傑克遜產生以下?

{ 
    start: 102394580192345 //milliseconds 
    startString: '2017-12-31 17:35:22' 
} 

回答

2

你可以編寫一個自定義的Jackson串行器,然後必須在應用程序中註冊。之後,每個這種dataType的出現都會以這種方式進行序列化。即使要序列化的數據類型在另一個數據類型中。 (就像你的例子)

注意:我沒有爲LocalDateTime編寫它,因爲我在我的應用程序中爲ZonedDateTime編寫它。根據您的需求重寫它應該不是一件難事。

public class ZonedDateTimeSerializer extends JsonSerializer<ZonedDateTime> 
{ 

    @Override 
    public void serialize(ZonedDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException 
    { 
    gen.writeStartObject(); 
    gen.writeFieldName("timestamp"); 
    gen.writeString(Long.toString(value.toInstant().toEpochMilli())); 
    gen.writeFieldName("offset"); 
    gen.writeString(value.getOffset().toString()); 
    gen.writeFieldName("zone"); 
    gen.writeString(value.getZone().toString()); 
    gen.writeFieldName("ts"); 
    gen.writeString(StringUtils.convertZonedDateTimeToISO8601String(value)); 
    gen.writeEndObject(); 
    } 

} 

然後將其註冊爲傑克遜的ObjectMapper這樣的:

objectMapper = new ObjectMapper(); 
    SimpleModule module = new SimpleModule("MyModule"); 
    module.addSerializer(ZonedDateTime.class, new ZonedDateTimeSerializer()); 
    objectMapper.registerModule(module); 

雖然在這個過程中,我建議建立一個生產者(CDI),將始終與這串返回objectMapper默認添加。但我會離開這個任務你來研究;)

+1

聽起來完全像我所需要的,明天我會試試。 thx –

2

一個簡單的辦法是自己做字符串轉換爲一個額外的JSON字段:

public class DomainObject { 
    private LocalDateTime start; 

    @JsonProperty("startString") 
    public String formatStartDate() { 
    // use a date formatter to format the date as string here 
    } 
} 

傑克遜將序列start正常,和你已添加額外的JSON字段startString

+1

我想指出,未來的讀者,這種解決方案也很好。然而,只有當你知道你只需要該用例一次並且只在該位置時纔是首選。如果你知道你需要在多個地方或一般的自定義序列化,自定義傑克遜串行器是首選的選項。 _in我的觀點_ 仍然是您的解決方案+1。 – Nico