不一致的 JSON api 返回某种类型的对象列表或此对象类型的单个实例。我想创建一个能够将此内容解析为 List<A>
的通用方法(使用 jackson )。
例如,第一个变体是:
{ "error": "message" }
第二个变体:
[{ "error": "message" }, /* ... */]
我的方法的类型签名必须如下所示:
<A> List<A> eitherObjectOrList(String content, Class<A> c);
最佳答案
public static void main(String[] args) throws Exception {
String oneJson = "{ \"error\": \"message\" }";
String arrJson = "[{ \"error\": \"message\" }, { \"error\": \"message2\" }]";
List<Resp> result = eitherObjectOrList(oneJson, Resp.class);
System.out.println(result);
result = eitherObjectOrList(arrJson, Resp.class);
System.out.println(result);
}
public static <A> List<A> eitherObjectOrList(String content, Class<A> c) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
return mapper.readValue(
content,
mapper.getTypeFactory().constructCollectionType(List.class, c)
);
}
Resp 是一个
public static class Resp {
private String error;
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
@Override
public String toString() {
return "Resp{" +
"error='" + error + '\'' +
'}';
}
}
关于java - 使用 Jackson 将作为列表或对象的 JSON 内容解析为 List<A>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53590352/