java - java中判断json属性是列表还是对象
问题描述
我想将从服务返回的 JSON 转换为 java 对象类。但是,我在同一个 JSON 属性中得到了两种类型,并因此得到以下错误Expected begin array but it was begin object
。如何在为我的 java 类解析 JSON 之前进行测试?下面的 JSON 示例:
{
"name": "ROMEU",
"age": "24",
"phone": "xx xxxx xxxx",
"family": [
{
"kinship": "brother",
"age": "20"
},
{
"kinship": "sister",
"age": "25"
}
]
}
{
"name": "ROMEU",
"age": "24",
"phone": "xx xxxx xxxx",
"family": {
"kinship": "mother",
"age": "20"
}
}
解决方案
假设您使用的是 Jackson,您可以使用ACCEPT_SINGLE_VALUE_AS_ARRAY
final ObjectMapper mapper = new ObjectMapper()
.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
如果使用 GSON,类似
JSONObject response=new JSONObject(res);
if(res.get("family") instanceOf JSONObject) {
// code for JSONObject
} else if(res.get("family") instanceOf JSONArray) {
// code for JSONOArray
}
推荐阅读
- html - 如何在使用:active 类为 tanslateX() 属性设置动画时使按钮可点击?
- assembly - 如何在汇编8086中显示中断向量表?
- mysql - 在mysql中创建表时发生错误
- php - 我需要获取在 Opencart 3.0.2.0 for flat.php(shipping) 的购物车中添加的产品类别
- verilog - 使用变量值作为网络名称
- angular - 加载的图像没有在 Angular 中设置
- linux - 为卷 lvm 创建文件系统 xfs 时出错
- firebase - 使用 Firebase 接收通知
- c# - 如何使用 CodeGenerator 实现接口的所有成员
- charts - 如何使用 HighStock 在时间序列数据上绘制水平条/列/线?