首页 > 解决方案 > 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"
  }
} 

标签: javaarraysjsonjsonparser

解决方案


假设您使用的是 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
}

推荐阅读