1

I'm using Spring Boot with JPA and Jodatime.

Currently I have a model attribute annotated like this:

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

When serialized, the JSON is becoming:

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

I want to know if there is a way to serialize that attribute to be like this:

{
  "startTime": "12:00"
}

I have tried to put that @JsonFormat annotation, but it does not seem to work.

inafalcao
  • 1,415
  • 1
  • 11
  • 25
  • Possible duplicate of [How to serialize Joda DateTime with Jackson JSON processer?](http://stackoverflow.com/questions/3269459/how-to-serialize-joda-datetime-with-jackson-json-processer) – Savior Apr 05 '16 at 02:34

1 Answers1

4

You could do something like:

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

and then create 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"));
    }

}

This requires the jackson-databind library.

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.databind-version}</version>
    </dependency>
Peter Kirby
  • 1,915
  • 1
  • 16
  • 29