Home > OS >  Why does Jackson destructure my LocalDateTime when I add a CorsMapping configuration in Spring?
Why does Jackson destructure my LocalDateTime when I add a CorsMapping configuration in Spring?

Time:07-11

I have a simple API which handles Entity objects (shown below).

@Data
public class Entity {

  private LocalDateTime createdAt;

}

A controller which looks like the following:

@RestController
@AllArgsConstructor
class MyController {

  private final EntityService entityService;

  @GetMapping
  Flux<Entity> getEntities() {
    return entityService.all(); // returns all entities from some storage location...
  }

}

When I make a GET request to my API, I receive the following response:

{
  "createdAt": "2022-07-10T20:39:01.147915"
}

Now, my API is designed to be consumed from a different origin, which means I need to add some custom CORS config to my application.

For this, I have created the following:

@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
        .allowedMethods("GET", "POST")
        .allowedOrigins("http://localhost:3000");
  }
}

After adding this and changing nothing else in my API the response changes to:

{
  "createdAt": [
    2022,
    7,
    10,
    20,
    39,
    1,
    147915000
  ]
}

Does anyone know what is causing this behaviour? Thanks

CodePudding user response:

Try to put this annotation on your 'createdAt' field

` @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", shape = JsonFormat.Shape.STRING)`

And check out this question

  • Related