繁体   English   中英

GSON 解析不确定类型的序列化实例

[英]GSON parse serialized instance of uncertain type

在以下示例中,我必须解析 json 字符串,它是 object 的序列化,可能是 CustomClass_1 或 CustomClass_2 的实例,但我事先并不知道。 问题如下:

  • 我得到一个异常 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 预期 BEGIN_RAIN_OBJECT
  • the json string produced by GSON from the instance of CustomClass_2 is just the string ["item"] as if the object was just an instance of the superclass ArrayList

有什么建议可以实现我想要的吗?

class CustomClass_1 {
  String type;

  CustomClass_1(){
    type = "CustomClass_1";
  }
}

class CustomClass_2 extends ArrayList<String> {
  String type;

  CustomClass_2(){
    super();
    type = "CustomClass_2";
    this.add("item");
  }
}

public class DeserializationTest {

  @Test
  public void testIncomingMessageParsing(){
    String serialized_object = receive();
    CustomClass_1 cc1 = null;
    CustomClass_2 cc2 = null;
    try{
      cc1 = (new Gson()).fromJson(serialized_object, CustomClass_1.class);
    } catch (Exception e){
      e.printStackTrace();
    }
    try{
      cc2 = (new Gson()).fromJson(serialized_object, CustomClass_2.class);
    } catch (Exception e){
      e.printStackTrace();
    }
    if (cc1 != null && cc1.type.equals("CustomClass_1")) {
      System.out.println("It's a CustomClass_1.");
    } else if (cc2 != null && cc2.type.equals("CustomClass_2")) {
      System.out.println("It's a CustomClass_2.");
    }
  }

  String receive(){
    CustomClass_1 cc1 = new CustomClass_1();
    CustomClass_2 cc2 = new CustomClass_2();
    String serialized_object = "";
    Gson gson = new Gson();
    boolean head = (new Random()).nextBoolean();
    if (head){
      serialized_object = gson.toJson(cc1);
    } else {
      serialized_object = gson.toJson(cc2);
    }
    return serialized_object;
  }
} // end of class

首先,在要反序列化的数据与字符串数据不匹配的“错误”情况下抛出JsonSyntaxException ,因此可能可以忽略此情况,因为其他情况将正确反序列化字符串。 如果您需要抑制此异常,那么您可能会考虑使用一些不同的方法来定义您的对象。 Collection s 将被序列化为对象而不是 arrays 时,也可能出现这种情况,因此完成了“错误”的反序列化。

其次,根据这个来源,GSON 似乎从Collection (和List )派生并添加字段到派生类,只会序列化Collection的元素。 对于这种类,您可能需要自定义TypeAdapter实现来实现所需的 JSON 字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM