3

Main Goal:

I would like to serialize 2 POJO fields from within 1 field's CustomSerializer while avoiding the default serialization of the second field and keeping the POJO as clean as possible.

POJO:
public class Entity{

    // The existence of @JsonProperty on either fields does not change the behavior.
    
    @JsonSerialize(using=MySerializer.class)
    @HashTo("hashedKuku")
    private String kuku;

    private String hashedKuku;

    // Public Getters & Setters for both fields

}
MySerializer:
public class MySerializer extends JsonSerializer<String> {

    // Some code including try-catch clauses omitted for simplicity.

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeString(value);
        final String currentFieldName = gen.getOutputContext().getCurrentName();
        final Field declaredField = gen.getCurrentValue().getClass().getDeclaredField(currentFieldName);
        final HashTo annotation = declaredField.getAnnotation(HashTo.class);
        final String hashFieldName;
        if(annotation!=null && !(hashFieldName=annotation.value()).isEmpty()) {
            // gen.writeStringField(hashFieldName, new Hasher().getHashedValue(value));
            // OR
            serializers.defaultSerializeField(hashFieldName, new Hasher().getHashedValue(value), gen);              
    }

}

Expected Result:

{
    "kuku": "someValue",
    "hashedKuku": "someHash"
}

Actual Result:

{
    "kuku": "someValue",
    "hashedKuku": "someHash",
    "hashedKuku": null
}

The Problem:

MySerializer does the job, and the defualt serializer serializes hashedKuku as well.

Constraints:

  • MySeializer should be on the field itself and not a class-level serializer.
  • Keep the POJO as clean as possible (have only 2 annotations on kuku field).

What I've Tried: (Solutions that work but are not good enough)

  1. Using JsonProperty.Access.WRITE_ONLY:
  @JsonProperty(JsonProperty.Access.WRITE_ONLY)
  private String hashedKuku;
  1. Using @JsonIgnore on the field:
  @JsonIgnore
  private String hashedKuku;
  1. Using @JsonIgnore on the getter:
  @JsonIgnore
  public String getHashedKuku() {
    return hashedKuku;
  }
  1. Many more solutions that I will skip as they're either an overengineering or also not good enough.

Ultimate Solution:

Register the serialization of hashedKuku so the default serializer skips it.
Maybe get access to the default serializer in MySerializer and serialize hashedKuku through it?



What I've Researched:
Julian Broudy
  • 320
  • 3
  • 15

0 Answers0