K
K
kidar22015-03-05 11:11:15
Java
kidar2, 2015-03-05 11:11:15

Java, Jackson desirialization. How to handle generec type based on interface from java.util?

public class Bla
{
  public SortedSet<Comparable> values;
}

The values ​​field contains an object of the following class:
public class ArraySortedSet<E extends Comparable<E>>
    extends AbstractSet<E>
    implements SortedSet<E>, Serializable
{
  
}

Serializes fine.
{
"values": [2]
}
But deserialization fails with this error:
com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of java.lang.Comparable, problem: abstract types either need to be mapped to concrete types , have custom deserializer, or be instantiated with additional type information
How should Jackson be configured to parse json ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikolai Pavlov, 2015-03-05
@gurinderu

The problem is that you don't have type information basically because List.class doesn't have any information about Generic.
There are two ways to solve this problem:
1. Extend the ArrayList class, which will not work with generic
2. Use ObjectWriter (like mapper.writerForType(listType).writeValueAsString())
listType can be done through TypeFactory or TypeReference

D
DigitalSmile, 2015-03-05
@DigitalSmile

It seems to be written in Russian in English letters ...
Comparable is an interface and it needs an implementation, otherwise Jackson will not be able to create an object for you (where will it put the fields from json?). Find (write) the implementation of this interface you need and use it in deserialization, something like this:

mapper.readValue(objectJson, mapper.getTypeFactory().constructCollectionType(SortedSet.class, <ВАША РЕАЛИЗАЦИЯ Comparable>))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question