简体   繁体   中英

Jackson and generic types inside a subclass

I am rewriting the question since I figured out the actual error in the code.

This is a fully functional example of my issue (I am using Jackson 2.9.0):

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import java.io.IOException;
import java.net.URL;
import java.util.List;

public class MainClass {

    public static class SubClass<TYPE> {
        private List<TYPE> values;

        public List<TYPE> getValues() {
            return values;
        }

        public void setValues(List<TYPE> values) {
            this.values = values;
        }
    }

    public static class Foo {
        private String name;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }

    private SubClass<Foo> propertyFoo;

    public SubClass<Foo> getPropertyFoo() {
        return propertyFoo;
    }

    public void setPropertyFoo(SubClass propertyFoo) {
        this.propertyFoo = propertyFoo;
    }

    public static void main(String args[]) throws IOException {
        URL url = System.class.getResource("/testFoo.json");
        ObjectMapper mapper = new ObjectMapper();
        ObjectReader reader = mapper.readerFor(MainClass.class);
        MainClass mainClass = reader.readValue(url);
        mainClass.getPropertyFoo().getValues().forEach(foo -> {
           System.out.println(String.format("name: %s", foo.getName()));
        });
    }
}

Note the missing type parameter:

public void setPropertyFoo(SubClass propertyFoo)

instead of

public void setPropertyFoo(SubClass<Foo> propertyFoo)

The first form compiles but produces the following exception when run

Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to MainClass$Foo

As I wrote in the newly edited post, my issue was with that setter. Although it compiles it was throwing an exception since Jackson couldn't find the right type to use for the inner objects.

Fixing

public void setPropertyFoo(SubClass propertyFoo)

to

public void setPropertyFoo(SubClass<Foo> propertyFoo)

I know it's a trivial error but since I already spent all this time on finding the issue, maybe it will help somebody. If a mod/admin thinks this is not helpful, I can delete it whole.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM