0

我正在尝试通过使用将持久化到我的 MongoDB 中的 JSON 数组反序列化为 Java 对象Jackson。我发现许多提到的教程通过添加来处理这种多态性:

@JsonTypeInfo(use=Id.CLASS,property="_class")

到一个Super-class。但是,就我而言,我无法修改Super-class. 那么,是否有一些解决方案可以在不修改的情况下解决它Super-class?这是我的代码:

public class User {

    @JsonProperty("_id")
    private String id;
    private List<Identity> identities; // <-- My List contains objects of an abstract class; Identity
    public User(){
        identities = new ArrayList<Identity>();
    }
    public static Iterable<User> findAllUsers(){
        return users().find().as(User.class); // Always give me the errors
    }
    /*More code*/
}

它总是给我错误 - Can not construct instance of securesocial.core.Identity, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information

4

1 回答 1

0

您可以使用@JsonDeserilize 注解将具体实现类绑定到抽象类。如果你不能修改你的抽象类,你可以使用Jackson Mix-in 注释告诉 Jackson 如何找到实现类。

这是一个例子:

public class JacksonAbstract {
    public static class User {
        private final String id;
        private final List<Identity> identities;

        @JsonCreator
        public User(@JsonProperty("_id") String id, @JsonProperty("identities") List<Identity> identities) {
            this.id = id;
            this.identities = identities;
        }

        @JsonProperty("_id")
        public String getId() {
            return id;
        }

        public List<Identity> getIdentities() {
            return identities;
        }
    }

    public static abstract class Identity {
        public abstract String getField();
    }

    @JsonDeserialize(as = IdentityImpl.class)
    public static abstract class IdentityMixIn {
    }

    public static class IdentityImpl extends Identity {
        private final String field;

        public IdentityImpl(@JsonProperty("field") String field) {
            this.field = field;
        }

        @Override
        public String getField() {
            return field;
        }
    }

    public static void main(String[] args) throws IOException {
        User u = new User("myId", Collections.<Identity>singletonList(new IdentityImpl("myField")));
        ObjectMapper mapper = new ObjectMapper();
        mapper.addMixInAnnotations(Identity.class, IdentityMixIn.class);
        String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(u);
        System.out.println(json);
        System.out.println(mapper.readValue(json, User.class));
    }
}
于 2014-05-10T09:40:55.503 回答