skip to Main Content

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


  1. 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;
    }
    
    Login or Signup to reply.
  2. 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)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search