Manish Soni Manish Soni - 1 month ago 9
Java Question

Not Able To Deserialize the JSON response to Arrya Of Objects

I am working on a code which consume the json and convert it to Objects .
For example say my json response is as below :-

String carJson ="{\"car\" : [{ \"brand\" : \"Mercedes\", \"doors\" : 5 },{ \"brand\" : \"Tata\", \"doors\" : 4 }] }";

Its array of car actually .

I have written below code to deserialize it to Java Objects :-

ObjectMapper objectMapper = new ObjectMapper();

objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

List<Car> jsonToCarList = objectMapper.readValue(carJson, new TypeReference<List<Car>>() {});
jsonToCarList.forEach(System.out::println);


This is mine Car Class :-

public class Car {
@JsonProperty("car")
private List<CarType> car;

public Car(@JsonProperty("car") List<CarType> car) {
this.car = car;
}

@JsonProperty("car")
public List<CarType> getCar() {
return car;
} }


CarType is as below :-

class CarType {

@JsonProperty("brand")
private String brand;

@JsonProperty("doors")
private String doors;

public CarType(String brand, String doors) {
this.brand = brand;
this.doors = doors;
}

public CarType() {

}

@JsonProperty("brand")
public String getBrand() {
return brand;
}

@JsonProperty("doors")
public String getDoors() {
return doors;
}
}


What's wrong here i am not getting . I am getting below error :-

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
at [Source: {"car" : [{ "brand" : "Mercedes", "doors" : 5 },{ "brand" : "Tata", "doors" : 4 }] }; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:762)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:758)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.handleNonArray(CollectionDeserializer.java:275)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:216)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:206)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:25)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3066)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2168)

Answer

You are attempting to deserialize into the wrong type:

List<Car> jsonToCarList = objectMapper.readValue(carJson, new TypeReference<List<Car>>() {});

should be

Car jsonToCar = objectMapper.readValue(carJson, Car.class);

The List you want is in the Car class you posted.

Comments