简体   繁体   中英

How do I edit the ResponseEntity of a Get-Request in Java Spring?

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.

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 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM