问题描述
我正在学习 Spring MVC RESTAPI,谁能解释一下 Jackson 库如何自动将对象列表转换为 JSON 格式。我无法弄清楚 Jackson 库何时开始发挥作用,以及从对象列表到 JSON 格式的转换是如何发生的,因为我将响应作为列表发送,但以某种方式将其转换为 JSON。有人可以解释一下这个过程吗?谢谢。
我添加的杰克逊图书馆:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1</version>
</dependency>
模型类:
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;
} }
控制器类:
@RestController 公共类 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}",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;
} }
当我请求 getCountries() 方法时,它只是发送 JSON 数据,即使该方法的数据类型是 List,这是怎么发生的?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)