0

My class looks like this,

@Getter
@ToString
@EqualsAndHashCode
public class Clazz {

    private String a;
    private long b;
    private CustomObject c;
    private List<String> d;

    @Builder
    @JsonCreator
    public Clazz(@JsonProperty(“a”) String a,
                     @JsonProperty(“b”) long b,
                     @JsonProperty(“c”) CustomObject c,
                     @JsonProperty(“d”) List<String> d) {

        this.a = a; 
        this.b = b; 
        this.c = c; 
        this.d = d; 
    }
}

I am getting issue while de-serialise CustomObject. How can i write custom serialiser and De-serialiser just for CustomObject?

ObjectMapper that I am using for de-serialisation and serialisation,

        objectMapper = spy(JsonMapper.builder()
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                .addModule(new GuavaModule())
                .addModule(new ParameterNamesModule())
                .serializationInclusion(JsonInclude.Include.NON_NULL)
                .activateDefaultTyping(ptv, ObjectMapper.DefaultTyping.NON_CONCRETE_AND_ARRAYS)
                .build());

I cannot alter the CustomObject class, hence need to handle the serialisation/deserialisation here in this class only.

Thank you in advance.

Anamika Patel
  • 135
  • 2
  • 6
  • 1
    First, the `@JsonProperty` is redundant because it is identical with variable name. Second, you can just annotate `CustomObject` with `@JsonSerialize` or `@JsonDeserialize` to use custom serializer or deserializer. – LHCHIN Jan 27 '22 at 06:15

1 Answers1

0

You can use the following annotation on top of CustomObject field in your Clazz

@JsonSerialize(using = CustomObjectSerializer.class)
private CustomObject c;
public class CustomObjectSerializer extends StdSerializer<CustomObject> {
 public CustomObjectSerializer() {
        this(null);
    }
  
    public CustomObjectSerializer(Class<CustomObject> t) {
        super(t);
    }

    @Override
    public void serialize(
      Item value, JsonGenerator jgen, SerializerProvider provider) 
      throws IOException, JsonProcessingException {
 
        jgen.writeStartObject();
        jgen.writeNumberField("id", value.id);
        jgen.writeStringField("name", value.name);
        jgen.writeEndObject();
    }
}

or register that serializer as follows

SimpleModule module = new SimpleModule();
module.addSerializer(CustomObject.class, new CustomObjectSerializer());
objectMapper.registerModule(module);

Check following resources:

  1. https://www.baeldung.com/jackson-custom-serialization
  2. https://stackoverflow.com/a/20530302/2534090
  3. https://stackoverflow.com/a/10835504/2534090
JavaTechnical
  • 8,846
  • 8
  • 61
  • 97