I'm trying to write SpringBoot request to return json data.But I can't think of a better way to solve the desired result below.
I want to print it out:
{
{
"code": "200",
"msg": "success",
"data": {
"data": []
}
}
my code:
@Controller
@RequestMapping(value = "/index/property")
public class PropertyController {
@Autowired
PropertyService propertyService;
@RequestMapping(value = "list", method = RequestMethod.GET)
@ResponseBody
public Map<String,Object> getPropertyList(@RequestParam(defaultValue= "1") int pageNumber, @RequestParam(defaultValue= "5") int pageSize) {
Map<String,Object> map = new HashMap<>();
PageHelper.startPage(pageNumber, pageSize, true);
List<Property> propertyList = propertyService.queryList();
PageInfo<Property> info = new PageInfo<>(propertyList);
map.put("code","200");
map.put("msg","success");
map.put("data", info.getList());
return map;
}
}
json error format
{
"code": "200",
"msg": "success",
"data": []
}
CodePudding user response:
You are assigning the list to the map, so the response is a list. What you need to do instead is create a pojo with one variable named "data" of type list. Assign there the values via the setter and add in the map the new pojo object. The pojo should look like this:
import java.util.List;
public class MyPojo {
private List<String> data;
public List<String> getData() {
return data;
}
public void setData(List<String> data) {
this.data = data;
}
}
and then you should do something like:
MyPojo myPojo = new MyPojo();
myPojo.setData(info.getList());
map.put("data", myPojo);