简体   繁体   English

在 Spring 引导中返回 JSON?

[英]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.我正在尝试编写 SpringBoot 请求以返回 json 数据。但我想不出更好的方法来解决下面的预期结果。

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 json 错误格式

{
    "code": "200",
    "msg": "success",
    "data": []
}

You are assigning the list to the map, so the response is a list.您正在将列表分配给 map,因此响应是一个列表。 What you need to do instead is create a pojo with one variable named "data" of type list.您需要做的是创建一个 pojo,其中包含一个名为“data”的列表类型的变量。 Assign there the values via the setter and add in the map the new pojo object. The pojo should look like this:通过设置器分配值并在 map 中添加新的 pojo object。pojo 应该如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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