杰克逊解析器:忽略反序列化的类型不匹配 [英] Jackson Parser: ignore deserializing for type mismatch
问题描述
我正在通过 CakePHP的
[
{
"id": "42389",
"start": "0000-00-00",
"end": "0000-00-00",
"event_id": null,
"trip_id": "5791",
"location_id": "231552",
"user_id": "105",
"users_attending": "0",
"user_local": "0",
"Trip": {
"name": "Asdas"
},
"Event": [],
"Location": {
"name": "South Melbourne"
}
},
{
"id": "42392",
"start": "0000-00-00",
"end": "0000-00-00",
"event_id": "1218",
"trip_id": "4772",
"location_id": "271505",
"user_id": "105",
"users_attending": "3",
"user_local": "50",
"Trip": {
"name": "trip by 1059200"
},
"Event": {
"title": "SampleEvent 454",
"id": "1218"
},
"Location": {
"name": "Houston"
}
},
.......
]
问题是,解析器预期事件
对象,但如果它的空
那么它接收空数组。
The thing is that the parser expects Event
object but if its null
then it is receiving empty array.
由于通过生成响应汽车的CakePHP
,它在服务器端的很多地方进行更改。
Since the response is auto generated by cakephp
, it has to be changed at a lot of places on server side.
有没有什么简单的方法杰克逊忽略事件
属性如果空数组??
Is there any simple way for jackson to ignore Event
property if its an empty array??
编辑:
我曾尝试具有事件
名称的两个属性:一个阵列和其他对象,但同样没有奏效
I have tried having two properties with Event
name: one array and other object but that too didn't work.
推荐答案
一直以来,我都必须处理响应这样的许多对象,我终于与创建一个通用类径自这将返回一个解串器
为特定的类
。
Since, I had to handle response like this for many objects I finally went ahead with creating a generic class which would return a Deserializer
for a specific class
.
下面是我用什么
public class Deserializer<T> {
public JsonDeserializer<T> getDeserializer(final Class<T> cls) {
return new JsonDeserializer<T> (){
@Override
public T deserialize(JsonParser jp, DeserializationContext arg1) throws IOException, JsonProcessingException {
JsonNode node = jp.readValueAsTree();
if (node.isObject()) {
return new ObjectMapper().convertValue(node, cls);
}
return null;
}
};
}
}
这篇关于杰克逊解析器:忽略反序列化的类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!