How to return a set of objects with Spring Boot?

后端 未结 3 1349
情书的邮戳
情书的邮戳 2020-12-09 05:52

I did a lesson about Spring Boot and it works perfectly. But what if I want to return a set of objects ? I tried doing this but it doesn\'t work. How can I do i

3条回答
  •  既然无缘
    2020-12-09 06:20

    Let Say we have list of CarDetails Pojo and we want to return them back

    @RestController
    public class CarDetailController {
      @GetMapping("/viewAllCarDetailList")
        public List retrieveAllCarDetails() {
            List contacts = new ArrayList();
    
            CarDetail objt = new CarDetail();
            objt.setCarModel("hyundai");
            objt.setSubModel("I10");
            CarDetail objt2 = new CarDetail();
            objt2.setCarModel("hyundai");
            objt2.setSubModel("I20");        
            contacts.add(objt);
            contacts.add(objt2);
            return contacts;
        }
    }
        public class CarDetails {
    
                private String carModel;
                private String subModel;
    // Will haave Setter getter and hash code equls method
    //and constructor
        }
    

    This JSON will be output:-

    [
        {
            "carModel": "hyundai",
            "subModel": "I10"
        },
        {
            "carModel": "hyundai",
            "subModel": "I20"
        }
    ]
    

提交回复
热议问题