Shivansh Narayan
Shivansh Narayan

Reputation: 516

How to serialize and deserialize a list of objects using Jackson

I am getting an error while deserializing an array of objects.

ans int the below expression is a List<Restaurant> type

String json = obj.writeValueAsString(ans);

I am getting error in the below line

List<Restaurant> all= Arrays.asList(obj.readValue(reslistjson,Restaurant[].class));

The error - Cannot deserialize instance of com.crio.qeats.dto.Restaurant[] out of START_OBJECT token at [Source: (String)"{"restaurantId":"12","name":"A2B","city":"Electronic City","imageUrl":"www.google.com","latitude":20.015,"longitude":30.015,"opensAt":"18:00","closesAt":"23:00","attributes":["Tamil","South Indian"]}"; line: 1, column: 1]

Upvotes: 1

Views: 576

Answers (1)

TechFree
TechFree

Reputation: 2954

JSON input in your example is an object not an array. For your JSON data, this would work:

List<Restaurant> all= Arrays.asList(objectMapper.readValue(json,Restaurant.class));

A JSON like this is an array of objects and your original code would work:

String json = "[{..data1 goes here....}, {..data2 goes here....}]";
List<Restaurant> all= Arrays.asList(objectMapper.readValue(json,Restaurant[].class));

Upvotes: 1

Related Questions