【问题标题】:Spring MVC: How to correctly create the entity for following JSON responseSpring MVC:如何为以下 JSON 响应正确创建实体
【发布时间】:2017-08-26 13:20:06
【问题描述】:

我在为 Spring MVC RestTemplate.exchange 请求正确创建模型/实体时遇到问题,该请求将对应于此 JSON 响应:

{
    "resourceLookup": [
        {
            "version": 0,
            "permissionMask": 1,
            "creationDate": "2017-08-16T12:52:30",
            "updateDate": "2017-08-16T12:52:30",
            "label": "",
            "description": "",
            "uri": "",
            "resourceType": ""
        },
        {
            "version": 5,
            "permissionMask": 1,
            "creationDate": "2017-08-16T11:34:04",
            "updateDate": "2017-08-17T08:27:02",
            "label": "",
            "description": "",
            "uri": "",
            "resourceType": ""
        }
    ]
}

我创建了以下模型:

报告类(getters/setters 省略):

public class Report implements Serializable {
    private Long version;
    private String permissionMask;
    private Date creationDate;
    private Date updateDate;
    private String label;
    private String description;
    private String url;
    private String resourceType;

    public Report() {
    }

ResourceLookup 类:

public class ResourceLookup implements Serializable {
    List<Report> reports;

    public ResourceLookup() {
    }

    public List<Report> getReports() {
        return reports;
    }

    public void setReports(List<Report> reports) {
        this.reports = reports;
    }
}

最后回复是reports=null。如果我用这段代码返回String,一切都很好:

restTemplate.exchange(serverUrl, HttpMethod.GET, httpEntity, String.class).getBody();

我需要将它正确映射到模型,以便我可以将格式正确的 JSON 返回给我的其他 API。

【问题讨论】:

  • 旁注,permissionMask 被定义为字符串,但在 JSON 中它看起来是一个数字。
  • @tima 谢谢。很好地记录和修复。
  • 为什么Report 的数组应该命名为resourceLookup 而不是reports?这就是您在 JSON 输出中的内容。

标签: java json spring spring-mvc


【解决方案1】:

试试这个方法:

public class ResourceLookup implements Serializable {
    List<Report> resourceLookup;

    public ResourceLookup() {
    }

    public List<Report> getResourceLookup() {
        return resourceLookup;
    }

    public void setResourceLookup(List<Report> resourceLookup) {
        this.resourceLookup = resourceLookup;
    }
}

【讨论】:

    猜你喜欢
    • 2015-03-19
    • 1970-01-01
    • 2023-02-21
    • 2021-11-04
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    相关资源
    最近更新 更多