【问题标题】:How to hide fields with a condition in RESTful WS?如何在 RESTful WS 中隐藏带有条件的字段?
【发布时间】:2018-02-26 20:17:13
【问题描述】:

我有一个名为 Report 的类,我需要使用 RESTful WS 共享它。

  1. 一次完整的所有属性
  2. 仅在精简版中出现过一次

通常我会使用 @XmlTransient 之类的东西来隐藏字段,但这会阻止完整版本的工作。

有什么方法可以在输出之前设置条件或预过滤字段类型,以免影响同一类的其他用途?

我的报告类如下所示:

public class Report {
    private String reportId;
    private String title;
    private String content;
    private Date created;
    private Date modified;
...
}

完整报告的 RESTful 共享如下所示:

@GET
@Path("/{reportId}")
public Report getReport(@PathParam("reportId") String reportId) {
    return Mock.getReport(reportId);
}

我需要的完整输出如下所示:

{
   "reportId": "d83badf3",
   "title": "The tales of lamaru",
   "content": "When once the great Imgur started his journey...",
   "created": 1519672434866,
   "modified": 1519672434866
}

我需要的简短输出应该是这样的:

{
   "reportId": "d83badf3",
   "title": "The tales of lamaru"
}

实现这一点需要什么?

【问题讨论】:

标签: java rest web-services get jax-rs


【解决方案1】:

为什么不使用继承

父母

public class Report {
    private String reportId;
    private String title;
}

孩子

public class FullReport extends Report{
    private String content;
    private Date createdp;
    private Date modified;
}

当您需要完整的报告集返回类型为FullReport 否则Report

【讨论】:

    【解决方案2】:

    当您想从 JSON 序列化和反序列化过程中排除某些类成员时,Jackson 有两种不同的注释可供使用。这两个注解是@JsonIgnore 和@JsonIgnoreProperties。 @JsonIgnoreProperties 是类级别的注释,它期望要排除的属性将以字符串列表的形式显式指示。 @JsonIgnore 而是成员级别或方法级别的注解,它期望被排除的属性被一一标记。

    试试这个。

    public class Report {
        private String reportId;
        private String title;
        @JsonIgnore
        private String content;
        @JsonIgnore
        private Date created;
        @JsonIgnore
        private Date modified;
    ...
    }
    

    【讨论】:

    • 是的,@XmlTransient 在这种情况下与@JsonIgnore 具有相同的效果。虽然我需要 (1) 完整的报告 JSON 和 (2) 简化的报告 JSON。如果我在 Report 类中添加@JsonIgnore,我达到了(2)的目标,但没有达到(1)的目标。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多