我正在尝试将一些JSON反序列化为泛型类。结构大致如下:
public abstract class AbstractRequest implements Constants
{
public abstract Class<?> getClazz();
}
public class GetTransaction extends AbstractTransactionRequest
{
@Override
public Class<Transaction> getClazz()
{
return Transaction.class;
}
}
Transaction
类如下:
public class Transaction implements Serializable
{
@SerializedName("_id")
private String id;
private int amount;
@SerializedName("details")
private Map<String, String> transactionDetails;
private class Details {
private String issuer;
@SerializedName("redirect_url")
private String redirectUrl;
@SerializedName("approval_url")
private String approvalUrl;
}
}
所有类都稍微复杂一点,但我删除了无关的变量。
这是一个JSON示例:
{
"_id": "2740096e-58a0-4677-8947-84fcc54cfaad",
"amount": 456,
"details": {
"issuer": "MYBANK",
"redirect_url": "https://example.com/redirect/MYBANK",
"approval_url": "https://example.com/v1/transaction/2740096e-58a0-4677-8947-84fcc54cfaad/MYBANK/authorize"
}
}
现在,我通过执行
反序列化此代码response.setData(Gson.fromJson(this.getResponse(), this.request.getClazz()));
setData
接受Object
,getResponse
将JSON作为String
返回。然后我执行(Transaction) response.getData()
将数据转换为Transaction
。但是,这始终为空。谁能告诉我为什么?
对于可能令人困惑的代码感到抱歉!