Skip to content
Advertisement

How to write common pojo deserializer for json attribute which can be an object and an array both?

Background:

I am getting mismatchedInputException, when parsing json. com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type java.util.ArrayList<Data> from Object value (token JsonToken.START_OBJECT)

Problem:

nodes is a json-array which contains data, which can be either json-object or json-array .

I need to represent this correctly in POJO.

Things Tried: Map<String, Object>, List, ,@JsonDeserialize(using = NodeDeserializer.class)

Below is my nested json document for ref.

JavaScript

Below is Pojo Java classes and Runner class, I am using for SER/DE for above Json

Data.java

JavaScript

Node.java

JavaScript

Parent.java

JavaScript

Test.java

JavaScript

Runner Class

JavaScript

Advertisement

Answer

How to write common pojo deserializer for json attribute which can be an object and an array both?

It is possible if you use the JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY deserialization feature consisting of an override for the DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature which allows deserialization of JSON non-array values into single-element Java arrays and Collections. So you can annotate the data field of your Node class to obtain the expected behaviour:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement