Sunday, 26 August 2018

return list of json spring boot rest controller

Let Say we have list of CarDetails Pojo and we want to return them back
@RestController
public class CarDetailController {
  @GetMapping("/viewAllCarDetailList")
    public List<CarDetail> retrieveAllCarDetails() {
        List<CarDetail> contacts = new ArrayList<CarDetail>();

        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"
    }
]

output in Postman

https://stackoverflow.com/questions/41719142/how-to-return-a-set-of-objects-with-spring-boot


No comments:

Post a Comment