2016-04-05 129 views
1

我使用JPA和Jodatime的Spring Boot。joda的傑克遜序列化LocalTime

目前我有註解這樣一個模型屬性:

@Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalTime") 
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "HH:mm") 
private LocalTime startTime; 

當系列化,JSON正成爲:

{ 
"startTime" : { 
     "hourOfDay" : 12, 
     "minuteOfHour" : 0, 
     "secondOfMinute" : 0, 
     "millisOfSecond" : 0, 
     "chronology" : { 
     "zone" : { 
      "fixed" : true, 
      "id" : "UTC" 
     } 
     } 
} 

我想知道如果有序列化屬性的方式是這樣的:

{ 
    "startTime": "12:00" 
} 

我試過把那個@JsonFormat註釋掉,b它似乎並不奏效。

+0

的可能的複製[如何序列喬達日期時間與傑克遜JSON processer?](http://stackoverflow.com/questions/3269459/how-to-serialize-joda-datetime-with-jackson-json- processer) – Savior

回答

3

你可以這樣做:

@JsonSerialize(using = MyLocalTimeSerializer.class) 
private LocalTime startTime; 

,然後創建MyLocalTimeSerializer.class:

public class MyLocalTimeSerializer extends JsonSerializer<LocalTime> { 

    @Override 
    public void serialize(
      LocalTime time, 
      JsonGenerator gen, 
      SerializerProvider arg2) throws IOException, JsonProcessingException { 
     gen.writeString(time.toString("HH:mm")); 
    } 

} 

這就要求傑克遜數據綁定庫。

<dependency> 
     <groupId>com.fasterxml.jackson.core</groupId> 
     <artifactId>jackson-databind</artifactId> 
     <version>${jackson.databind-version}</version> 
    </dependency> 
+0

工作,謝謝! – inafalcao

+0

不應該擴展JsonSerializer ? – kandan

+0

@kandan是!我會解決它! –