How to enforce ACCEPT_SINGLE_VALUE_AS_ARRAY in jackson's deserialization process using annotation

后端 未结 4 2096
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 14:27

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 b

4条回答
  •  佛祖请我去吃肉
    2020-12-01 14:50

    I would create a custom JsonDeserializer where I would deal with both cases and annotate value class property with the deserializer.

    Deserializer:

    public class StringListDeserializer extends JsonDeserializer>{
    
        @Override
        public List deserialize(JsonParser parser, DeserializationContext ctxt)
                throws IOException, JsonProcessingException {
    
            List ret = new ArrayList<>();
    
            ObjectCodec codec = parser.getCodec();
            TreeNode node = codec.readTree(parser);
    
            if (node.isArray()){
                for (JsonNode n : (ArrayNode)node){
                    ret.add(n.asText());
                }
            } else if (node.isValueNode()){
                ret.add( ((JsonNode)node).asText() );
            }
            return ret;
        }
    }
    

    MyClass:

    public class MyClass {
        .
        @JsonDeserialize(using = StringListDeserializer.class)
        private List value;
        .
    }
    

    Hope it helps.

    BTW: If there is a way how to deal with such a case with just an annotation, I also want to know it.

提交回复
热议问题