1

in my Spring Framework project I am writing web services (Apache CXF) where I am (de)serializing inputs and outputs using JacksonJsonProvider.

I want to serialize DTO objects differently each time. I know I can use custom serializer and override some of Jackson's functionality but my requirements that I want to do it differently every time!

Example:

here is my DTO class I want to serialize

public class MyDTO {

    private Long sessionId;
    private String firstName;
    private String lastName;
    private String email;
    ...
}

here are my two webservice methods:

@GET
@Path("/example1")
public Response myWsMethodExample1(...) {
    MyDTO dto = new MyDto();
    ...
    return Response.status(Status.OK).entity(dto).type(MediaType.APPLICATION_JSON).build();
}

@GET
@Path("/example2")
public Response myWsMethodExample2(...) {
    MyDTO dto = new MyDto();
    ...
    return Response.status(Status.OK).entity(dto).type(MediaType.APPLICATION_JSON).build();
}

I want that API call on /example1 produces:

{ "sessionId": 1, "fistName": "John", "lastName": "Smith", "email": "john@smith.com" }

and call on /example2 produces the same DTO without, say, email and sessionId:

{ "fistName": "John", "lastName": "Smith" }

How can I do this?

How can I achieve this without actually having to use 2 different DTOs for a response? Is that even possible? Annotations like @JsonIgnoreProperty won't work because that would ignore a property permanently.

I am looking for the most elegant solution. Many thanks:-)

user3732445
  • 241
  • 1
  • 10

1 Answers1

2

Use @JsonView to filter fields depending on the context of serialization. When returning data to a REST client, depending on which REST service was called, we need to limit which data will be serialized while using the same data model.

for more details can check this question on stackoverflow

and also there is a good article about @JsonView and Spring security integration on baeldung.com to filter exposing data based on security

Saeed Alizadeh
  • 1,417
  • 13
  • 23
  • many thanks! This is what I was looking for. Although, is it okay to put annotations on DTO classes? The DTOs are in a separate module and now I have to include Jackson's dependency in the pom.xml there. What is the best practice? It solves the issue though. – user3732445 Jan 14 '20 at 18:19