如何从Java中的泛型类型反序列化JSON对象?

时间:2015-11-20 21:10:59

标签: java json generics mapping gson

我正在尝试映射JSON响应,如下所示:

{
    object: {
    id: 1
    name: "my name"
    email: "username@mail.com"
    username: "username"
    password: "password"
    mobile: "##########"
    fbAccessToken: "----------"
    img: null
    }
    errorMessage: ""
    successMessage: ""
    technicalErrorMessage: ""
    error: false
  }

所以我写了这个方法:

private <T> ResponseEntity<T> processedRequest(HttpRequestBase requestBase, Class<T> tClass) throws IOException {
        HttpResponse response = httpClient.execute(requestBase);
        HttpEntity entity = response.getEntity();
        Reader reader = new InputStreamReader(entity.getContent());

        Type type = new TypeToken<ResponseEntity<T>>() {}.getType();

        ResponseEntity<T> responseEntity = gson.fromJson(reader, type);

        return responseEntity;
    }

基于ResponseEntity类:

public class ResponseEntity<T> {

private T object;
private boolean isError;
private String errorMessage;
private String successMessage;
private String technicalErrorMessage;

public ResponseEntity() {
    setSuccessMessage("");
    setError(false);
    setErrorMessage("");
    setTechnicalErrorMessage("");
}

public T getObject() {
    return object;
}

public void setObject(T object) {
    this.object = object;
}

public boolean isError() {
    return isError;
}

public void setError(boolean error) {
    this.isError = error;
}

public String getErrorMessage() {
    return errorMessage;
}

public void setErrorMessage(String errorMessage) {
    this.errorMessage = errorMessage;
}

public String getTechnicalErrorMessage() {
    return technicalErrorMessage;
}

public void setTechnicalErrorMessage(String technicalErrorMessage) {
    this.technicalErrorMessage = technicalErrorMessage;
}

public String getSuccessMessage() {
    return successMessage;
}

public void setSuccessMessage(String successMessage) {
    this.successMessage = successMessage;
}}

但是我得到的结果为ResponseEntity<LinkedTreeMap>,对象是(Key->Value)的映射,而不是由ResponseEntity<T>类型发送的实际映射对象。

下面的图片是调试器中出现的内容:

image from debugger

1 个答案:

答案 0 :(得分:0)

GSON应该如何理解,它应该使用哪个类来代替T以及&#34;实际映射的对象是由Type&#34发送的?填补它的领域?对于Java中的泛型,我们有type erasure,因此在运行时无法理解它是什么T。没办法,所以gson只使用泛型Map<String, String>()

看看对此question的回复,情况相同。