An inconsistent JSON api returns me either a list of objects by some type or a single instance of this object type. I want to create a generic method that is capable of parsing this content as a List<A>
(using Jackson).
So for example, the first variant would be:
{ "error": "message" }
And the second variant:
[{ "error": "message" }, /* ... */]
The type signature of my method would have to look something like this:
<A> List<A> eitherObjectOrList(String content, Class<A> c);
答案 0 :(得分:1)
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 + '\'' +
'}';
}
}