Search code examples
javajsonspringjacksondto

Custom JSON serialization in Spring Framework and Apache CXF


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": "[email protected]" }

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


Solution

  • 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