有没有一种方法来使用注释在类中的列表属性使用ACCEPT_SINGLE_VALUE_AS_ARRAY的Jackson?我正在使用Spring并得到以下异常
ACCEPT_SINGLE_VALUE_AS_ARRAY的Jackson
嵌套的异常是com.fasterxml.jackson.databind.JsonMappingException:无法从VALUE_STRING令牌中反序列化java.util.ArrayList的实例
假设我有一个如下课程:
public class MyClass { private List < String > value; }
我的JSON结构如下:
情况1:
[{"operator": "in", "value": ["Active"], "property": "status"}]
情况2:
[{"operator": "like", "value": "aba", "property": "desc"}]
在反序列化时,我应该使用什么注释来使框架知道我希望这两种情况被视为相同。
更新: 为了使内容更加清晰,我将更新内容移到了这篇文章的答案中。
我只是在回答自己的问题。答案之一是升级到更高版本,以便我可以使用注释。由于项目的依赖关系限制,我无法执行此操作。
结果,基于Michal Foksa的答案,我通过创建自定义解串器解决了我的问题。其如下:
On my property:
@JsonDeserialize(using = CustomStringDeserializer.class) private List<String> value;
And my Deserializer:
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); } }
你可以使用@JsonFormat批注,
public class MyClass { @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY) private List<String> value; }
要使用此功能,你需要拥有Jackson版本min 2.7.0。你还可以使用其他可用的JsonFormat功能
min 2.7.0
对于2.6.x版本
@Autowired private ObjectMapper mapper; //... mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
Initializer Class
Jackson
Bean Configuration
deserialization