Jackson dynamic type array objects or object?

It comes to me in a controller json an object. How to write a deserializer

{
    "type": "array",
    "value": ["value1", "value2"]
}


{
    "type": "not_array",
    "value": "value1"
}



public class Dto {
    private String type;
    private Object value;
}

Ответы (1 шт):

Автор решения: Alexandr

Можете включить DeserializationFeature#ACCEPT_SINGLE_VALUE_AS_ARRAY если Вы используете Jackson.

package com.somepackage;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Setter;
import lombok.ToString;

class Main {

    @Setter
    @ToString
    public static class Dto {
        private String type;
        private String[] value;
    }

    public static void main(String[] args) throws Exception {
        final String json1 =
                "{\"type\": \"array\",\"value\": [\"value1\", \"value2\"]}";
        final String json2 =
                "{\"type\": \"not_array\",\"value\": \"value1\"}";

        final ObjectMapper mapper =
                new ObjectMapper()
                        .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
        final Dto dto1 = mapper.readValue(json1, Dto.class);
        System.out.println(dto1);
        final Dto dto2 = mapper.readValue(json2, Dto.class);
        System.out.println(dto2);
    }
}

Результат:

Main.Dto(type=array, value=[value1, value2])
Main.Dto(type=not_array, value=[value1])
→ Ссылка