Jackson mapping Object or list of Object depending on json input

后端 未结 2 617
旧巷少年郎
旧巷少年郎 2020-12-09 10:17

I have this POJO :

public class JsonObj {

    private String id;
    private List location;


    public String getId() {
        return id;         


        
2条回答
  •  时光说笑
    2020-12-09 10:37

    Update: Mher Sarkissian's soulution works fine, it can also be used with annotations as suggested here, like so:.

    @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
    private List item;
    

    My deepest sympathies for this most annoying problem, I had just the same problem and found the solution here: https://stackoverflow.com/a/22956168/1020871

    With a little modification I come up with this, first the generic class:

    public abstract class OptionalArrayDeserializer extends JsonDeserializer> {
    
        private final Class clazz;
    
        public OptionalArrayDeserializer(Class clazz) {
            this.clazz = clazz;
        }
    
        @Override
        public List deserialize(JsonParser jp, DeserializationContext ctxt)
                throws IOException {
            ObjectCodec oc = jp.getCodec();
            JsonNode node = oc.readTree(jp);
            ArrayList list = new ArrayList<>();
            if (node.isArray()) {
                for (JsonNode elementNode : node) {
                    list.add(oc.treeToValue(elementNode, clazz));
                }
            } else {
                list.add(oc.treeToValue(node, clazz));
            }
            return list;
        }
    }
    

    And then the property and the actual deserializer class (Java generics is not always pretty):

    @JsonDeserialize(using = ItemListDeserializer.class)
    private List item;
    
    public static class ItemListDeserializer extends OptionalArrayDeserializer {
        protected ItemListDeserializer() {
            super(Item.class);
        }
    }
    

提交回复
热议问题