如何使用注释在jackson的反序列化过程中强制执行A​​CCEPT_SINGLE_VALUE_AS_ARRAY [英] How to enforce ACCEPT_SINGLE_VALUE_AS_ARRAY in jackson's deserialization process using annotation

查看:834
本文介绍了如何使用注释在jackson的反序列化过程中强制执行A​​CCEPT_SINGLE_VALUE_AS_ARRAY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在类的List属性上使用注释在Jackson中使用ACCEPT_SINGLE_VALUE_AS_ARRAY?我正在使用Spring并获得以下异常

Is there a way to use annotation on a List property in a class to use ACCEPT_SINGLE_VALUE_AS_ARRAY in Jackson? I'm using Spring and getting the below exception

嵌套异常是com.fasterxml.jackson.databind.JsonMappingException:无法反序列化java.util的实例。 ArrayList超出VALUE_STRING标记

假设我有一个类如下:

public class MyClass {
.
.
private List<String> value;
.
.
}

我的JSON结构如下:

And my JSON structures are as below:

案例1:

[{"operator": "in", "value": ["Active"], "property": "status"}]

案例2:

[{"operator": "like", "value": "aba", "property": "desc"}]

我应该使用什么注释让框架知道我希望在反序列化时将这两种情况视为相同

What annotation should I use to let the framework know I want these 2 cases to be treated the same when deserializing

更新:
为了更加清晰,我在此帖中将更新移至答案。

UPDATE: I moved the updates to an answer in this post for more clarity.

推荐答案

为了清楚起见,我只是回答了我自己的问题。其中一个答案是升级到更高版本,以便我可以使用注释。由于项目的依赖性限制,我无法做到这一点。

I'm just answering my own question for clarity. One of the answers was to upgrade to the higher version so that I can use annotations. I cannot do it due to dependency restrictions of my project.

结果,根据Michal Foksa的回答,我通过创建自定义反序列化器解决了我的问题。如下所示:

As a result, based on Michal Foksa answer I solved my problem by creating a custom deserializer. Its as below:

在我的财产上:

@JsonDeserialize(using = CustomStringDeserializer.class)
private List<String> value;

我的解串器:

public class CustomStringDeserializer extends JsonDeserializer<List<String>>{

    @Override
    public List<String> deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(DeserializationFeature. ACCEPT_SINGLE_VALUE_AS_ARRAY);
        return mapper.readValue(p, List.class);
    }

}

这篇关于如何使用注释在jackson的反序列化过程中强制执行A​​CCEPT_SINGLE_VALUE_AS_ARRAY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆