1

Is there any out of the box way to deserialize a singleton json array into a java pojo of the same type?

for example, I would like the following json:

[{"eventId": "event1", "timestamp": 1232432132}]

to be deserialized into the following java POJO:

class Event {
  String eventId;
  long timestamp;
}

I tried using the following class:

class Event {
  String eventId;
  long timestamp;

  public Event(@JsonProperty("eventId") String event, 
               @JsonProperty("timestamp") long timestamp)
    //fields init
  }

  @JsonCreator
  public Event(List<Event> singletonList)
    //take first element in list and set its fields on this
  } 

but this fails with: om.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.ArrayList out of FIELD_NAME token

I know I can wrap the Event POJO with some other class like this:

class EventWrapper {
   Event event;

   @JsonCreator   
   EventWrapper(List<Event> events) {
     this.event = events.get(0);
   }  

but I would like to avoid that (as well as avoid custom deserializer)

Any help will be much appreciated.

yaarix
  • 490
  • 7
  • 18
  • What about this : https://stackoverflow.com/questions/6349421/how-to-use-jackson-to-deserialise-an-array-of-objects ? – Fabien Jul 02 '20 at 12:47
  • @Fabien thanks, but I don't want to get a java list/array, i want to get a simple POJO. I want to extract the (single) element from the array and i want this logic to be performed in the deserialization process so i will end up with a POJO and not an array – yaarix Jul 02 '20 at 13:12
  • Then I think that you'll need a custom deserializer, I don't think that there is an out of the box solution for this. Why do you want to avoid a custom deserializer? – Fabien Jul 02 '20 at 13:28
  • Ok. Thanks. I don't want a list since i have an infrastructure who knows how to deal with a pojo and im trying to avoid changing it if i can – yaarix Jul 03 '20 at 13:06

1 Answers1

1

you can get List by following this, instead of creating additional class,

    import com.fasterxml.jackson.databind.ObjectMapper;
    ObjectMapper mapper = new ObjectMapper();
    List<Event> myObjects = Arrays.asList(mapper.readValue(json, Event[].class));