0

let's say i have two objects: Person and ReqSingUp, and ReqSingUp contains Person.

Now if i try:

Person p=new Person("dan","lala");
ReqSingUp reqSingUp=new ReqSingUp(p);
String s = gson.toJson(reqSingUp,ReqSingUp.class);
Object o = gson.fromJson(s, Object.class);

if (o instanceof ReqSingUp) {
    System.out.println("it's ReqSingUp");
}
if (o instanceof Person ) {
    System.out.println("it's person");
}

it does not satisfy any condition (not instanceof ReqSingUp and not instanceof Person ).

Is there a way to know which type it is?

Thanks in advance.

hochl
  • 12,524
  • 10
  • 53
  • 87
Idan
  • 901
  • 4
  • 13
  • 29
  • No. I don't think there is a way. May be one work around is use one of the json tag to represent type of object. – kosa Apr 30 '12 at 19:14
  • Have you looked at the guide? This may help: https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types – TJR Apr 30 '12 at 19:16
  • Isn't this a variation of this question? http://stackoverflow.com/questions/3629596/deserializing-an-abstract-class-in-gson – John Munsch Apr 30 '12 at 19:21

1 Answers1

2

No, there is no way to directly know it.

This because the information contained in a JSon file doesn't contain directly any type information about the object that is serialized in there. That's why you usually provide the class when reading a JSon file, as in

fromJSon(myObject, MyClass.class)

This indeed creates problem even when reading collection of arbitrary types or genericized objects.

Jack
  • 131,802
  • 30
  • 241
  • 343