Remove some keys when converting from custom type into Map using Jackson's convertValue

Viewed 187

I have a rather simple Java object that I would like to convert it into a Map<String, Object> using Jackson's convertValue(fromValue, toValueTypeRef) — this is rather trivial.

At the same time, there are some fields/members (e.g.: createdOn and modifiedOn) I would like to remove from the resultant Map, but I can't remove them in all (de)serialization routines. I was wondering if there is a way to tell Jackson to do that, rather than removing them "by hand". I've usually seen @JsonView used for such purposes, but I think it doesn't work with convertValue — or I'm still unable to configure it correctly.

This is how I'm doing the conversion:

@NoArgsConstructor
public final class CustomTypeMapper {
  private static final TypeReference<Map<String, Object>> MAP_TYPE_REFERENCE = new TypeReference<>() { };

  private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); // ...with some customizations

  public Map<String, Object> convertFrom(final CustomType input) {
    // OBJECT_MAPPER.writerWithView(Views.Public.class);
    return OBJECT_MAPPER.convertValue(input, MAP_TYPE_REFERENCE);
  }
}

CustomType looks roughly like this:

@Getter
@Builder
@Jacksonized
public final class CustomType {
  @JsonProperty("id")
  private String id;

  @JsonProperty("user")
  private User user;

  ...

  @Builder.Default
  @JsonProperty("created_on") // TODO: Exclude this field/member some times
  @JsonView(Views.Internal.class)
  private final Instant createdOn = Instant.now();

  @Builder.Default
  @JsonView(Views.Internal.class)
  @JsonProperty("modified_on") // TODO: Exclude this field/member some times
  private Instant modifiedOn = Instant.now();
}
0 Answers
Related