简体   繁体   中英

Returning JSON in Spring Boot?

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM