使用Java 8和Jackson,我试图从这里解析JSON:
问题是,有一个值有时是一个空数组,有时候是一个HashMap。我在下面粘贴了两个摘录,查看每个中的cor_icon:
"2630775": {
"id": "2630775",
"label": "breakfast grill",
"description": "breakfast sandwiches, turkey sausage and bacon, home fries, pork sausage and bacon, omelets made to order with whole eggs, egg whites, eggbeaters and assorted fillings",
"zero_entree": "0",
"cor_icon": {
"18": "humane"
},
或者:
"4779080": {
"id": "4779080",
"label": "sweet chili vegan soup\nchicken egg drop soup",
"description": "",
"zero_entree": "0",
"cor_icon": {
"1": "vegetarian",
"4": "vegan"
},
相反:
"2630777": {
"id": "2630777",
"label": "morning pastries",
"description": "assorted danish, muffins, bagels, coffee cakes and tea breads",
"zero_entree": "0",
"cor_icon": [],
"ordered_cor_icon": [],
对于我的Java setter:
@JsonSetter("cor_icon")
public void setCorIcon(HashMap ci)
{
cor_icon = ci;
}
或更好:
@JsonSetter("cor_icon")
public void setCorIcon(HashMap<String, String> ci)
{
cor_icon = ci;
}
当有数据时这种方法很好,但是当没有数据时,当我得到“cor_icon”时:[]杰克逊抛出一个异常,说它无法从cor_icon反序列化HashMap。如果我将cor_icon更改为ArrayList,那么当有数据时,Jackson会抱怨它无法从cor_icon反序列化ArrayList。
那么诀窍是什么?
答案 0 :(得分:0)
您需要指定对JSON数组和JSON对象都有效的类型。两个显而易见的选择是java.lang.Object
和JsonNode
:在第一种情况下,您将获得List
或Map
(并且需要投射);后一种情况ArrayNode
或ObjectNode
。