选项1
您可以通过更改Response
代码和启用SerializationFeature.WRAP_ROOT_VALUE
+设置来完成此操作DeserializationFeature.UNWRAP_ROOT_VALUE
这是演示:
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
Response resp = mapper.readValue(json, Response.class);
}
public abstract static class Car implements Serializable {
public String color;
}
public static class Ford extends Car {
@JsonProperty("ford_property")
public String fordProperty;
}
public static class Audi extends Car {
@JsonProperty("audi_property")
public String audiProperty;
}
@JsonRootName("myobj")
public static class Response implements Serializable {
public List<Audi> audi;
public List<Ford> ford;
}
选项 2
不要更改结构中的任何内容,不需要WRAP_ROOT_VALUE
,但这会将对象反序列化 2 次
public static class Response implements Serializable {
private Map<String, List<Car>> myObj;
@JsonAnySetter
private void setter(String key, JsonNode value) {
try {
if (key.equals("ford")) {
myObj.put(key, mapper.readValue(value.toString(),
new TypeReference<List<Ford>>() {}));
} else if (key.equals("audi")){
myObj.put(key, mapper.readValue(value.toString(),
new TypeReference<List<Audi>>() {}));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
选项 3
自定义反序列化器与上面Response
的代码几乎相同@JsonAnySetter
,但可以在反序列化器中对其进行优化。