所以使用我正在使用的这个api我经常会遇到包含一个数组或对象字段的json,而且我不确定如何以正确的方式处理它。
我的json中有一个数组是
这是一个让事情更清晰的例子:
无:
{
"what": "kittens",
"why": "I don't meow",
"kittens": []
}
之一:
{
"what": "kittens",
"why": "I don't meow",
"kittens": {
"name": "Ser Pounce",
"gender": "male"
}
}
许多:
{
"what": "kittens",
"why": "I don't meow",
"kittens": [
{
"name": "Ser Pounce",
"gender": "male"
},
{
"name": "Mr. Snuffles",
"gender": "male"
}
]
}
现在,如果不是这种情况,第二个例子看起来像这样
{
"what": "kittens",
"why": "I don't meow",
"kittens": [
{
"name": "Ser Pounce",
"gender": "male"
}
]
}
我可以使用POJO
public class Kittens
{
public String what;
public String why;
public List<Kitten> kittens;
public static class Kitten
{
public String name;
public String gender;
}
}
然后以标准方式反序列化所有内容:
Kittens kittens = objectMapper.readValue(good_kitten, Kittens.class);
因此,另一种方法是使用树模型并手动进行大量类型检查(使用JsonNode.isArray()
等。)
这不可行但是因为会有很多开销,它不会很优雅,我提到当然还有一些嵌套:
{
"what": "kittens",
"why": "I don't meow",
"kittens": [
{
"name": "Ser Pounce",
"gender": "male",
"kittens": []
},
{
"name": "Mr. Snuffles",
"gender": "male",
"kittens": {
"name": "Waffles",
"gender": "female",
"kittens": [
{
"name": "Mittens",
"gender": "male",
"kittens": []
},
{
"name": "Winston",
"gender": "male",
"kittens": {
"name": "Fiona",
"gender": "female",
"kittens": []
}
}
]
}
}
]
}
现在我真的喜欢定义如下的模型并完成它
public class NestedKittens
{
public String what;
public String why;
public List<Kitten> kittens;
public static class Kitten
{
public String name;
public String gender;
public List<Kitten> kittens;
}
}
但这不起作用,因为在json中有普通的旧小猫对象应该有List<Kitten>
。
那么,是否有任何注释或配置可以让jackson在需要时自动从Kitten
转换为List<Kitten>
?
答案 0 :(得分:5)
解决方案结果非常简单:
objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);