Jackson desrialize when JsonProperty is sometimes array and sometimes a single Object

时光毁灭记忆、已成空白 提交于 2019-12-04 02:37:30
varren

If you enable DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY both

{"result": []} and

{"result": {}} can be parsed as

class Result{
   List result;
}

Documentation link

Feature that determines whether it is acceptable to coerce non-array (in JSON) values to work with Java collection (arrays, java.util.Collection) types. If enabled, collection deserializers will try to handle non-array values as if they had "implicit" surrounding JSON array. This feature is meant to be used for compatibility/interoperability reasons, to work with packages (such as XML-to-JSON converters) that leave out JSON array in cases where there is just a single element in array. Feature is disabled by default.

Demo how to use it for OP input jsons and POJOs:

ObjectMapper mapper = new ObjectMapper()
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
Result result = mapper.readValue(Result.class;

Can be used with @JsonFormat above class or field if you don't like mapper version for some reason

@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)

PS. Other SO questions about this problem: LINK

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!