I'm learning Spring MVC RESTAPI, Can anyone explain how the Jackson library automatically converts the list of objects to the JSON format. I can't figure out when the Jackson library comes into play and how the conversion happens from a list of objects to JSON format because I am sending the Response as a List but somehow it converts it into JSON. Can someone explain the process? Thank you.
The Jackson Library I've added :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1</version>
</dependency>
Model Class :
public class Country{
int id;
String countryName;
public Country(int i, String countryName) {
super();
this.id = i;
this.countryName = countryName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
} }
Controller Class :
@RestController public class CountryController {
@RequestMapping(value = "/countries", method = RequestMethod.GET,headers="Accept=application/json")
public List getCountries()
{
List listOfCountries = new ArrayList();
listOfCountries=createCountryList();
return listOfCountries;
}
@RequestMapping(value = "/country/{id}", method = RequestMethod.GET,headers="Accept=application/json")
public Country getCountryById(@PathVariable int id)
{
List listOfCountries = new ArrayList();
listOfCountries=createCountryList();
for (Country country: listOfCountries) {
if(country.getId()==id)
return country;
}
return null;
}
// Utiliy method to create country list.
public List createCountryList()
{
Country indiaCountry=new Country(1, "India");
Country chinaCountry=new Country(4, "China");
Country nepalCountry=new Country(3, "Nepal");
Country bhutanCountry=new Country(2, "Bhutan");
List listOfCountries = new ArrayList();
listOfCountries.add(indiaCountry);
listOfCountries.add(chinaCountry);
listOfCountries.add(nepalCountry);
listOfCountries.add(bhutanCountry);
return listOfCountries;
} }
When I request the getCountries() method, It just send the JSON data even though the Datatype of the method is List, How this is happening?