1

我采用了 java 流客户端 ( https://github.com/GetStream/stream-java ) 附带的 MixedType 示例代码,并使用 updateActivities 添加了更新步骤。更新后,存储在流中的活动会丢失“类型”属性。当您再次获得活动并且正在反序列化活动时,Jackson 会使用此属性。

所以我得到:

Exception in thread "main" Disconnected from the target VM, address: '127.0.0.1:60016', transport: 'socket' com.fasterxml.jackson.databind.JsonMappingException: Could not resolve type id 'null' into a subtype of [simple type, class io.getstream.client.apache.example.mixtype.MixedType$Match] at [Source: org.apache.http.client.entity.LazyDecompressingInputStream@29ad44e3; line: 1, column: 619] (through reference chain: io.getstream.client.model.beans.StreamResponse["results"]->java.util.ArrayList[1]) at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148) at com.fasterxml.jackson.databind.DeserializationContext.unknownTypeException(DeserializationContext.java:849)

请参阅此处我更新了示例:

https://github.com/puntaa/stream-java/blob/master/stream-repo-apache/src/test/java/io/getstream/client/apache/example/mixtype/MixedType.java

知道这里发生了什么吗?

4

1 回答 1

0

这里的问题是由 Jackson 发起的,由于 Java类型擦除,无法获取集合中对象的实际实例类型,如果您想了解更多信息,请阅读此问题:https ://github.com/FasterXML/ jackson-databind/issues/336(它也提供了一些可能的解决方法)。

解决它的最简单方法是type从子类中手动强制属性的值,如下例所示:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({
        @JsonSubTypes.Type(value = VolleyballMatch.class, name = "volley"),
        @JsonSubTypes.Type(value = FootballMatch.class, name = "football")
})
static abstract class Match extends BaseActivity {
    private String type;

    public String getType() {
        return type;
    }
}

static class VolleyballMatch extends Match {
    private int nrOfServed;
    private int nrOfBlocked;

    public VolleyballMatch() {
        super.type = "volley";
    }

    public int getNrOfServed() {
        return nrOfServed;
    }

    public void setNrOfServed(int nrOfServed) {
        this.nrOfServed = nrOfServed;
    }

    public void setNrOfBlocked(int nrOfBlocked) {
        this.nrOfBlocked = nrOfBlocked;
    }

    public int getNrOfBlocked() {
        return nrOfBlocked;
    }
}

static class FootballMatch extends Match {
    private int nrOfPenalty;
    private int nrOfScore;

    public FootballMatch() {
        super.type = "football";
    }

    public int getNrOfPenalty() {
        return nrOfPenalty;
    }

    public void setNrOfPenalty(int nrOfPenalty) {
        this.nrOfPenalty = nrOfPenalty;
    }

    public int getNrOfScore() {
        return nrOfScore;
    }

    public void setNrOfScore(int nrOfScore) {
        this.nrOfScore = nrOfScore;
    }
}
于 2016-09-15T15:38:26.850 回答