java - 使用 Jackson将作为列表或对象的 JSON 内容解析为列表
问题描述
解决方案
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 + '\'' +
'}';
}
}
推荐阅读
- docker - Dockerfile ENV 指令:键可以包含句点吗?
- python - Python Redis Stream 等到收到消息
- javascript - 使用 v-select 中选定的周期参数更新谷歌图表
- javascript - 使用 JS 从数组对象填充表
- vb.net - VB.net验证整数崩溃的文本框输入
- vue.js - Vue keep-alive有什么方法可以实现前向刷新,后向不刷新?
- docker - Jenkinsfile 启动和停止 docker 容器
- google-cloud-dataflow - 数据流管道遵循笔记本执行编号。无法更新管道
- javascript - 如果文本内容包含另一个正则表达式(例如,Javascript 正则表达式),则 Sed 的正则表达式会被破坏
- json - 访问不在索引中的熊猫数据框列