运行时GSON对象类型转换

时间:2018-10-22 12:56:49

标签: java gson

我有一个模板对象类型ExternalActionReqBean,该对象具有可以通过指示操作字段设置的任何类的对象

让我们说,如果action =“ FROZEN”,ExternalActionReqBean-> payload将为ExternalActionFrozenReqBean类类型,  如果将使用action =“ UNFROZEN” ExternalActionUnFrozenReqBean类类型。

如果有效载荷如下所示,那么实现此目标的最佳实践是什么?

  

{“ txnID”:“ txn”,“ action”:“冻结”,“资源”:“ PNSENDER”,“有效负载”:{“ 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;

}

1 个答案:

答案 0 :(得分:0)

我更改了ExternalActionReqBean类签名,将其类型转换为Generic,然后按如下所示使用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,您可以在“泛型的反序列化”下找到更多信息