Skip to content
This repository has been archived by the owner on Dec 3, 2020. It is now read-only.

Nested generic type in generic function #37

Open
Zkffkah opened this issue Mar 30, 2018 · 0 comments
Open

Nested generic type in generic function #37

Zkffkah opened this issue Mar 30, 2018 · 0 comments

Comments

@Zkffkah
Copy link

Zkffkah commented Mar 30, 2018

I have a json like this

    val JSON_LIST_STRING = """
{
  "code": "0",
  "msg": "Success",
  "subcode": "0",
  "data": [{
    "test": 10
  }
  ]
}
""".trimIndent()

model like this

    data class TestObject(val test: Int)

public class ApiResult<T> {
    private int code;
    private int subcode;
    private String msg;
    private T data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public boolean isOk() {
        return code == 0;
    }

    @Override
    public String toString() {
        return "ApiResult{" +
                "code='" + code + '\'' +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }

    public int getSubcode() {
        return subcode;
    }

    public void setSubcode(int subcode) {
        this.subcode = subcode;
    }
}

test code like this

  @Test
    fun testFunListGson() {

        val result = data<List<TestObject>>()
        assertThat(result.data[0].test).isEqualTo(10)
    }

    @Test
    fun testDirectListGson() {

        val result = gson.fromJson<ApiResult<List<TestObject>>>(JSON_LIST_STRING)
        assertThat(result.data[0].test).isEqualTo(10)
    }

    fun <T> data(): ApiResult<T> {
        return gson.fromJson(JSON_LIST_STRING)
    }

Expect testFunListGson will pass, but it failed like this

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.xxx.GsonTest$TestObject

It looks like it's not getting past the underneath generic type.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant