我正在从 Web 服务检索 JSON。有时 JSON 中的属性会作为对象返回,有时它是对象的数组。如何编写要反序列化的 Java 类,以使用 Jackson 的正确反序列化此属性ObjectMapper?我可以使用 ObjectMapper 来帮助解决这个问题吗?
带有对象的 JSON:
\n\n"results": {\n "account": {\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0"expiration": "2012-11-16"\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\nJSON 与集合
\n\n"results": {\n\xc2\xa0\xc2\xa0"account": [{\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0"expiration": "2012-11-16"\n }]\n}\nRun Code Online (Sandbox Code Playgroud)\n
您需要将该属性标记为 Java 数组或Collection,并启用 ACCEPT_SINGLE_VALUE_AS_ARRAY 功能:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature. ACCEPT_SINGLE_VALUE_AS_ARRAY);
ResultOb ob = mapper.readValue(jsonInput, ResultOb.class);
Run Code Online (Sandbox Code Playgroud)
如果遇到单个 JSON 对象,则会将其视为单元素 JSON 数组。
| 归档时间: |
|
| 查看次数: |
1376 次 |
| 最近记录: |