Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize List<Interface> with jackson

I want to deserialize json to class Foo:

class Foo {
   List<IBar> bars;
}

interface IBar {
   ...
}

class Bar implements IBar {
   ...
}

IBar has two implementations, but when deserializing I always want to use the first implementation. (This should ideally make the problem easier, because there is no runtime type checking required)

I am sure I can write custom deserializers, but felt there must be something easier.

I found this annotation, which works perfectly when there is no list.

@JsonDeserialize(as=Bar.class)
IBar bar;

List<IBar> bars; // Don't know how to use the annotation here.
like image 508
varunl Avatar asked Nov 08 '13 19:11

varunl


People also ask

Can Jackson serialize interface?

Jackson can serialize and deserialize polymorphic data structures very easily. The CarTransporter can itself carry another CarTransporter as a vehicle: that's where the tree structure is! Now, you know how to configure Jackson to serialize and deserialize objects being represented by their interface.

Does Jackson preserve array order?

Jackson mapper fill the ArrayList maintaining the order of JSON. If you want a different order you can use the annotation @JsonPropertyOrder.

What is Jackson deserialization?

Jackson is a powerful and efficient Java library that handles the serialization and deserialization of Java objects and their JSON representations. It's one of the most widely used libraries for this task, and runs under the hood of many other frameworks.

How do you deserialize an array of objects in Java?

We can easily deserialize JSON Array into Java Array by using the readValue() method of the ObectMapper class. In the readValue() method, we pass two parameters, i.e., jsonString and Student[]. class.


1 Answers

@JsonDeserialize(contentAs=Bar.class)
List<IBar> bars;
like image 80
varunl Avatar answered Sep 27 '22 01:09

varunl