我正在处理一个使用json并将其转换为Objects的代码。 例如,说我的json响应如下: -
String carJson =“{\”car \“:[{\”brand \“:\”Mercedes \“,\”doors \“:5},{\”brand \“:\”Tata \“, \“门\”:4}]}“;
实际上是它的汽车阵列。我在下面编写了代码,将其反序列化为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);
这是我的汽车类: -
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如下: -
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;
}
}
这里有什么不对,我没有得到。我收到以下错误: -
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)
答案 0 :(得分:1)
您正在尝试反序列化为错误的类型:
List<Car> jsonToCarList = objectMapper.readValue(carJson, new TypeReference<List<Car>>() {});
应该是
Car jsonToCar = objectMapper.readValue(carJson, Car.class);
您想要的列表位于您发布的Car类中。