运行时 GSON 对象类型转换

我有一个模板对象类型 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

@AllArgsConstructor

public class ExternalActionReqBean {


   private String txnID;

   private String action;

   private String resource;

   private Object payload;


}




@Data

public class ExternalActionFrozenReqBean {


   private List<String> msisdn_list;


}


@Data

public class ExternalActionUnFrozenReqBean {


   private String result;


}


翻过高山走不出你
浏览 158回答 1
1回答

开满天机

我已经更改了 ExternalActionReqBean 类签名,它的类型被转换为通用,而不是使用 TypeToken 如下。@Data@AllArgsConstructorpublic class ExternalActionReqBean<T> {&nbsp; &nbsp;private String txnID;&nbsp; &nbsp;private String action;&nbsp; &nbsp;private String resource;&nbsp; &nbsp;private T payload;}代码:&nbsp;if ("FROZEN".equals(externalActionReqBean.getAction())) {&nbsp; Type complexType = new TypeToken<ExternalActionReqBean<ExternalActionFrozenReqBean>>() {}.getType();&nbsp; ExternalActionReqBean<ExternalActionFrozenReqBean> result = GSON.fromJson(payload, complexType);}感谢https://futurestud.io/tutorials/gson-advanced-generics,您可以在“泛型反序列化”下找到更多信息
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java