我有一个模板对象类型 ExternalActionReqBean 有一个对象,可以通过指示操作字段设置任何类让我们说,如果 action="FROZEN" , ExternalActionReqBean->payload 将使用 ExternalActionFrozenReqBean 类类型,如果 action="UNFROZEN" ExternalActionUnFrozenReqBean 类类型将被使用。如果有效载荷如下所示,实现这一目标的最佳实践是什么?{"txnID":"txn","action":"FROZEN","resource":"PNSENDER","payload":{"msisdn_list":["xxxx","xxx","xxx"]}}ExternalActionReqBean externalActionReqBean = GSON.fromJson(payload, ExternalActionReqBean.class); if("FROZEN".equals(externalActionReqBean.getAction())){ // externalActionFrozenReqBean = GSON.fromJson(externalActionReqBean.getPayload(),ExternalActionFrozenReqBean.class); }@Data@AllArgsConstructorpublic class ExternalActionReqBean { private String txnID; private String action; private String resource; private Object payload;}@Datapublic class ExternalActionFrozenReqBean { private List<String> msisdn_list;}@Datapublic class ExternalActionUnFrozenReqBean { private String result;}
1 回答
开满天机
TA贡献1786条经验 获得超13个赞
我已经更改了 ExternalActionReqBean 类签名,它的类型被转换为通用,而不是使用 TypeToken 如下。
@Data
@AllArgsConstructor
public class ExternalActionReqBean<T> {
private String txnID;
private String action;
private String resource;
private T payload;
}
代码:
if ("FROZEN".equals(externalActionReqBean.getAction())) {
Type complexType = new TypeToken<ExternalActionReqBean<ExternalActionFrozenReqBean>>() {}.getType();
ExternalActionReqBean<ExternalActionFrozenReqBean> result = GSON.fromJson(payload, complexType);
}
感谢https://futurestud.io/tutorials/gson-advanced-generics,您可以在“泛型反序列化”下找到更多信息
添加回答
举报
0/150
提交
取消