Jackson ObjectMapper在反序列化泛型类型时抛出java.lang.ClassCastException:java.util.LinkedHashMap

时间:2018-01-12 16:08:48

标签: java json generics jackson

我正在尝试使用Jackson ObjectMapper反序列化Custom Generic Type类,但测试抛出以下异常。我知道jackson api无法找到正确的构造类型,但我不知道是什么在我的场景中纠正constrct类型。 我尝试使用constructCollectionType&很少有人,但它现在正在运作。所以任何帮助都将受到高度赞赏。

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.test.CsSpace
    at java.util.ArrayList.forEach(ArrayList.java:1249)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)

这是自定义Generic Type类

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Response<T> {

    private int totalResults;
    private List<T> results;

    public int getTotalResults() {
        return totalResults;
    }

    public void setTotalResults(int totalResults) {
        this.totalResults = totalResults;
    }

    public List<T> getResults() {
        return results;
    }

    public void setResults(List<T> results) {
        this.results = results;
    }
}

其中一种类型如下。

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Space {

    @JsonProperty("id")
    private String id;

    @JsonProperty("Building_ID")
    private String buildingId;

    //few more fields &its getter and setters
}

这是反序列化json的主要业务逻辑

public <T> List<T> getEntity(ConnectorArg arg, String bearerToken, String path, Response<T> gt) throws IOException, ConnectorException {
        String token = BEARER+bearerToken;
        String url = hostName+path;
        ObjectMapper mapper = new ObjectMapper();
        Response res = ClientBuilder
                .newClient()
                .register(JacksonFeature.class)
                .target(url)
                .request(MediaType.APPLICATION_JSON)
                .header(Authorization, token)
                .post(Entity.json(arg));
        if(res.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) {
            CsSpaceResponse<T> csSpaceRes = mapper.readValue(res.readEntity(String.class), gt.getClass()); 
            //throws the exception above line. Tried mapper.readValue(res.readEntity(String.class), mapper.getTypeFactory().constructCollectionType(List.class, gt.getClass()));
            return csSpaceRes.getResults();
        }else {
            throw new ConnectorException("Exception while connecting to "+url);
        }
    }

以下是我试图反序列化的JSON示例。

{
        "totalResults": 2,
        "results": [{
            "id": "1908",
            "Building_ID": "1234"
        }, {
            "id": "1909",
            "Building_ID": "12347"
        }]
    }

0 个答案:

没有答案