0

I have a small Java Springboot backend and a mySQL database. The data class for the objects to be saved in the database looks as follows:

    @Entity
    public class Product {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int id;
    
        private String name;
    
        private String category;
    
        private LocalDate expirationDate;
    
        // getters, setters ...

The GET method within the controller class looks like this:

@GetMapping("/products")
public ResponseEntity<Iterable<Product>> getProducts() {
   return ResponseEntity.ok(productRepository.findAll());
}

Now the json I get back when posting a GET-request formats the expirationDate property as int[], like this:

"expirationDate": [
            2023,
            1,
            22
        ]

How do I manage to format this while creating the json for it to look like yyyy-mm-dd, as this is the format I also use to POST it. Also, as I'm writing my frontend in Blazor (C#), I need a format that gets easily translated into a DateOnly property in the C# data class.

Turwaith
  • 67
  • 6
  • 1
    Isn't this a duplicate of https://stackoverflow.com/questions/29956175/json-java-8-localdatetime-format-in-spring-boot? – meriton Dec 30 '22 at 00:56

2 Answers2

2

change the controller to return List of products as follows:

@GetMapping("/products")
public ResponseEntity<List<Product>> getProducts() {
    return ResponseEntity.ok(productRepository.findAll());
}

Also, I recommend to use lombok and put @Data anotation on your Entity.

I just reproduce yours and you will got the data like this:

[
{
    "id": 1,
    "name": "Iphone",
    "category": "apple",
    "expirationDate": "2022-12-23"
},
{
    "id": 2,
    "name": "Samsung",
    "category": "samsung",
    "expirationDate": "2022-12-23"
}
]

Incase you need, this is your post mapping:

@PostMapping("/products")
public Product createProduct(@RequestBody Product product) {
    productRepository.save(product);
    return product;
}
  • I still get the date back as int[], even after implementing your code. I might just use a string for the date now and check the format in my frontend with some regex. For a beginner like me, it seems to be a lot of work to just get the date working, also considering I need to convert the date from the json into some C# data type in my front end. – Turwaith Dec 30 '22 at 01:12
  • can you give more details on your repository and also service? – Mani Movassagh Dec 31 '22 at 18:09
0

I think you are missing something with the serialisation, do you know which lib you are using to serialize data to json ? (If not, can you copy/paste your dependency config file ? (pom.xml if you use maven)

If you use jackson for example, you need to add specific dependencies to your project, to have a proper serialization of dates. (You can refer to Java 8 LocalDate Jackson format for instance)

E. Bavoux
  • 535
  • 1
  • 4
  • 11