Spring/Jackson + @JsonView: filter REST response

Let's say we have a class User:

public class User {
    private int id;
    private String name;
    private String password;
}

and we want to show on UI fields id and name, and we want to export fields name and password.

We need to add marker interface

public class User {
    private int id;
    private String name;
    private String password;

    public interface EXPORT {}
    public interface UI {}
}

and markup fields in POJO and controller methods:

public class User {
    @JsonView(User.UI.class)
    private int id;
    @JsonView({User.UI.class, User.EXPORT.class})
    private String name;
    @JsonView(User.EXPORT.class)
    private String password;
}
@JsonView(User.UI.class)
@RequestMapping(value = "/ui/{id}", method = RequestMethod.GET)
public User getUi(@PathVariable("id") int id) {
   return ...;
}
@JsonView(User.EXPORT.class)
@RequestMapping(value = "/export/{id}", method = RequestMethod.GET)
public User getExport(@PathVariable("id") int id) {
   return ...;
}

In case of pagination, we need custom serializer for Page:

public class PageSerializer extends StdSerializer {

    public PageSerializer() {
        super(PageImpl.class);
    }

    @Override
    public void serialize(PageImpl value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeStartObject();
        gen.writeNumberField("number", value.getNumber());
        gen.writeNumberField("numberOfElements", value.getNumberOfElements());
        gen.writeNumberField("totalElements", value.getTotalElements());
        gen.writeNumberField("totalPages", value.getTotalPages());
        gen.writeNumberField("size", value.getSize());
        gen.writeFieldName("content");
        provider.defaultSerializeValue(value.getContent(), gen);
        gen.writeEndObject();
    }
}
@Bean
public Module jacksonPageWithJsonViewModule() {
    SimpleModule module = new SimpleModule("jackson-page-with-jsonview", Version.unknownVersion());
    module.addSerializer(PageImpl.class, new PageSerializer());
    return module;
}

That's all. Result of getUi() will be {"id": 1, "name": "John"} and result of getExport() {"name": "John", "password": "secret"}

Leave a Reply

Your email address will not be published.