1

I was trying convert to my object to and from json but the default serializer, deserializer by jackson doesn't work.

How can I make this work? I understand I might need to write a custom serializer, deserializer. How can I do that? Is ther some annotation by adding which the code would work?

Here is the object:

@JsonDeserialize(keyUsing = mypairDeserializer.class)
@JsonSerialize(keyUsing = mypairSerializer.class)
HashMap<Set < Mypair > , List < Mypair > > obj;


public class ConditionSerializer extends JsonSerializer<Collection<mypair>> {

    @Override
    public void serialize(final Collection<mypair> conditionSet, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeFieldName("Pair");
        jsonGenerator.writeStartArray();
        for(final Condition condition: conditionSet) {
            jsonGenerator.writeString(mypair.toString());
        }
        jsonGenerator.writeEndArray();
        jsonGenerator.writeEndObject();
    }
}


public class mypairDeserializer extends KeyDeserializer {
    ObjectMapper mapper = new ObjectMapper();
    @Override
    public Collection<mypair> deserializeKey(final String key, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
        // return new mypair(key);
        return mapper.readValue(key, Collection.class);
    }
}
Bhavya Nag
  • 15
  • 3

1 Answers1

0

Maybe this can help you : https://www.baeldung.com/jackson-custom-serialization

You can create a custom jackson serializer class and set it on the object mapper used to serialize your object.

Florian S.
  • 280
  • 2
  • 5