gpt4 book ai didi

java - 适用于 Jackson 中任何列表的自定义解串器

转载 作者:行者123 更新时间:2023-12-02 03:03:07 24 4
gpt4 key购买 nike

我遇到列表中对象错误的问题。例如我有一个 JSON 模型:

{
"items": [
{
"id": 1,
"name": "Item1"
},
{
"id": 2,
"name": "Item2"
},
{
"id": [],
"name": "Item3"
}
]
}

和两个 POJO

data class BadList(val items: List<BadItem>)

data class BadItem(val id: Int, val name: String)

当然,当解析器偶然发现第三个元素时,我得到了异常

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.Integer out of START_ARRAY token
at [Source: {"items":[{"id":1,"name":"Item1"},{"id":2,"name":"Item2"},{"id":[],"name":"Item3"}]}; line: 1, column: 19] (through reference chain: my.package.BadList["items"]->java.util.ArrayList[2]->my.package.BadItem["id"])

谁知道如何解决这个问题?我想跳过那个错误的项目。

最佳答案

您可以编写自定义反序列化器并在其中实现反序列化逻辑,例如:

class ItemIdDeserialiser extends JsonDeserializer<Integer> {

@Override
public Integer deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
Object value = p.getCurrentValue();
//Check if it's Integer
if(value instanceof Integer){
return (Integer) value;
}
return null; //Or return first element if it's a non empty list
}
}

完成此操作后,您可以使用 @JsonDeserialise 注释该字段,以指示 jackson 使用您的类,例如:

class Item {

@JsonDeserialize(using = ItemIdDeserialiser.class)
private Integer id;
}

更新

如果你只想忽略序列化/反序列化中的字段,那么你可以用@JsonIgnore注释它,例如

class Item {

@JsonIgnore
private Integer id;
}

或者更好的是,从 pojo 中删除 id 并在类上添加 @JsonIgnoreProperties,例如:

@JsonIgnoreProperties(ignoreUnknown = true)
class Item {

}

它将自动忽略 json 中存在但在类中找不到的属性。

关于java - 适用于 Jackson 中任何列表的自定义解串器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42169379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com