Search code examples
javarestweb-servicesgetjax-rs

How to hide fields with a condition in RESTful WS?


I have a class called Report that I need to share using RESTful WS.

  1. once in full with all its attributes
  2. once in only a reduced version

Normally I'd use something like @XmlTransient to hide the fields, but this would prevent the full version from working.

Is there any way to set a condition or to kind of pre-filter fields just before the output so that it doesn't affect other uses of the same class?

My Report class looks like this:

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

The RESTful sharing for the full Report looks like this:

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

The full output I need looks like this:

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

The short output I need should look like this:

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

What is necessary to achieve this?


Solution

  • Why don't you use Inheritance?

    Parent

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

    Child

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

    When you need full report set return type as FullReport otherwise Report