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.
2
Answers
change the controller to return List of products as follows:
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:
Incase you need, this is your post mapping:
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)