3

My code is as below

@Data 
@Document(collection = "models")
public class Model {
  @Field(value = "modelDt")
  private LocalDateTime modelDate;
}

@Data
public class ModelDTO {
  private LocalDateTime modelDate;
}

@RestController
@RequestMapping("/api/v1/model")
public class ModelController {

  @Autowired 
  ModelService modelService;

  @GetMapping
  public List<ModelDTO> getModels() {
    return modelService.getAllModels();
  }
}

Used this almost everywhere where the JSON response is coming as a proper format like yyyy-mm-ddT00:00:00 , but in the above case I'm getting the date in the below format.

[
  {
    "modelDate": [
    YYYY,
    MM, 
    DD, 
    00,
    00,
    0000
    ]
  }
]

I've crossed checked my code with the ones where the proper format is being returned.

Pi53
  • 211
  • 1
  • 4
  • 11

2 Answers2

14

use below Jackson annotation on date fields

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
Gaurav Dhiman
  • 953
  • 6
  • 11
  • This worked. Why is it that in the above case it is required but other models didn't require any such annotation. Is there a way you can avoid this annotation and still get the desired result? – Pi53 May 07 '20 at 13:49
  • 1
    @Pi53 Can you show the models for which it's working automatically? – Eklavya May 07 '20 at 14:09
  • I bet there is no models for which it's working automatically! – Eduard Grigoryev Nov 11 '22 at 15:28
1

If you want LocalDateTime to always serialize in any format then follow the solution.

You can create a Serializer for LocalDateTime and add it ObjectMapper.Then always LocalDateTime serialize using JacksonLocalDateTimeSerializer.

public class JacksonLocalDateTimeSerializer extends StdSerializer<LocalDateTime> {

  private static final long serialVersionUID = 1355852411036457107L;

  private static final DateTimeFormatter formatter =
      DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

  public JacksonLocalDateTimeSerializer() {
    this(null);
  }

  protected JacksonLocalDateTimeSerializer(Class<LocalDateTime> type) {
    super(type);
  }

  @Override
  public void serialize(LocalDateTime value, JsonGenerator jsonGenerator,
      SerializerProvider serializerProvider) throws IOException {
    jsonGenerator.writeString(formatter.format(value));
  }

}

And add this in ObjectMapper to auto-apply for LocalDateTime field for all responses.

@Configuration
public class JacksonConfig {

  @Bean
  @Primary
  public ObjectMapper configureObjectMapper() {
    JavaTimeModule javaTimeModule = new JavaTimeModule();
    javaTimeModule.addSerializer(LocalDateTime.class, new JacksonLocalDateTimeSerializer());
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(javaTimeModule);
    return objectMapper;
  }
}
Eklavya
  • 17,618
  • 4
  • 28
  • 57