I want deserialize List<Contact> with custom deserialezer using jackson library. List<Document> and List<Good> should deserialize by default.
There is my class
public class Application implements Serializable {
//other fields
private List<Document> documents;
private List<Contact> contacts;
private List<Good> goods;
}
But I can't change it to add annotations. So I use mixin
public abstract class ApplicationMixin {
@JsonProperty("contactId")
private List<Contact> contacts;
}
Custom deserializer:
@JsonComponent
public class ContactsDeserializer extends JsonDeserializer<List<Contact>> {
@Override
public List<Contact> deserialize(JsonParser parser, DeserializationContext context) throws IOException {
List<Contact> contacts = new ArrayList<>();
//some logic
return contacts;
}
}
And during deserialization all lists try to use this custom deserializer. But I want it only for contacts. What can I do for this?
The observed behavior is caused by the type erasure. On runtime, Jackson cannot tell the difference between List<Contact>
, List<Document>
or any other List, so it applies the ContactsDeserializer to all of them. You will need to be more precise about what the deserializer should be applied to.
You can try the following:
@JsonComponent
annotation from the ContactsDeserializer
ApplicationMixin
, add @JsonDeserialize(using = ContactsDeserializer.class)
to the contacts
field.public abstract class ApplicationMixin {
@JsonProperty("contactId")
@JsonDeserialize(using = ContactsDeserializer.class)
private List<Contact> contacts;
}
Alternatively, you might consider creating a custom deserializer for the Contact
class instead of the List<Contact>
. If it's possible depends on the input JSON format.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments