简体   繁体   中英

GSON parse serialized instance of uncertain type

In the following example I have to parse a json string which is the serialization of an object that may be either instance of CustomClass_1 or of CustomClass_2 and I don't know it beforehand. The problems are as follows:

  • I get an exception com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY
  • 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

Any suggestion to achieve what I want?

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

First, the JsonSyntaxException is thrown in the "wrong" case where the data to deserialize does not match the string data, so maybe this can be ignored because the other case will deserialize the string correctly. If you need to suppress this exception, then you might consider using some different approach to define your objects. This might also be the case when Collection s will be serialized as objects and not as arrays and therefore the "wrong" deserialization is done.

Second, it seems that deriving from a Collection (and List ) and adding fields to derived classes, GSON will only serialize the Collection 's elements, according to this source . For this kind of classes, you might need a custom TypeAdapter implementation to achieve the desired JSON string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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