【问题标题】:The elements of collections of a deserialized JSON object are LinkedHashMap反序列化 JSON 对象的集合元素是 LinkedHashMap
【发布时间】:2018-11-06 10:34:12
【问题描述】:

我正在向控制器https://pastebin.com/d4SHZuZh 发送请求。使用此类中的 Builder 反序列化 JSON。 @JsonDeserialize(builder = ContributionNewRequest.Builder.class)

集合的元素是从MovieInfoDTO继承的? extends MovieInfoDTO对象。

当从例如获取项目时列表elementsToAdd

contribution.getElementsToAdd()
            .forEach(boxOffice -> {
                ...
            });

原来boxOffice 元素是一个java.util.LinkedHashMap 对象。

我在互联网上发现http://www.baeldung.com/jackson-collection-array 上提到了JSON 默认将集合的元素设置为LinkedHashMap

我需要做什么才能使对象的类型正确?

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.jonki.popcorn.common.dto.movie.BoxOffice
at java.util.ArrayList.forEach(ArrayList.java:1257) ~[na:1.8.0_171]

【问题讨论】:

    标签: java json spring spring-mvc spring-boot


    【解决方案1】:

    您应该自定义您的反序列化构建器。

    试试这样的

    public class CustomDeserializer extends StdDeserializer<List<? extends MovieInfoDTO>> {
        protected CustomDeserializer(Class<?> vc) {
            super(vc);
        }
    
        @Override
        public List<? extends MovieInfoDTO> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            ObjectMapper objectMapper = new ObjectMapper();
            String json = jsonParser.getText();
            TypeReference type = new TypeReference<List<? extends MovieInfoDTO>>() {};
            return objectMapper.readValue(json, type);
        }
    }
    

    最后在 elementsToAdd 属性之前添加 @JsonDeserialize(using = CustomDeserializer.class)

    希望对你有所帮助。

    【讨论】:

    • 我需要为list、map和set创建一个反序列化的三个类?
    • 我要如何提交Set &lt;String&gt; tags,我需要创建另一个类进行反序列化?一般来说,我必须为一个项目创建很多这样的类。
    【解决方案2】:

    尝试使用以下代码进行转换。

    public <T> List<T> jsonToObjectList(String json, Class<T> tClass) throws IOException {
                ObjectMapper objectMapper = new ObjectMapper();
                List<T> ts = objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, tClass));
                return ts;
            }
    

    【讨论】:

    • 我需要一个更自动化的方法,这样我就不必每次都通过这个方法手动传递对象。好的注释会很好。
    猜你喜欢
    • 2017-04-29
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多