1

I am using Gson to deserialize a class which is inherited from an abstract class.

Here is my code:

public abstract class Mammal {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName(){
        return name;
    }
}

public class Dog extends Mammal {
    public void bark(){

    }
}

public class Cat extends Mammal{

    public void mew(){

    }
}

public class Main {
    public static void main(String[] args) {
        Gson gson = new Gson();
        Mammal dog = new Dog();
        String toGson = gson.toJson(dog);
        Mammal aDog = gson.fromJson(toGson, Mammal.class);
    }
}

An exception is thrown when I run it, can someone tell me how to fix this?

Kev
  • 118,037
  • 53
  • 300
  • 385
user2716189
  • 63
  • 1
  • 6

1 Answers1

1

In line

Mammal aDog = gson.fromJson(toGson, Mammal.class);

you are trying to deserialize to instance of Mammal object, which cant be done because Mammal is abstract class which means it cant be instantiated.

You need either remove abstract keyword from Mammal class description or use non abstract class instead like Dog.class

Mammal aDog = gson.fromJson(toGson, Dog.class);
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • Thank you. Then if at runtime, I dont know what aDog's class is, I just know it is a subclass of Mammal, and I need to cast it to the right subclass, what should I do? – user2716189 Aug 26 '13 at 06:54
  • @user2716189 That is good question. You should ask it as separated thread, but before you do it check this [fragment of Gson tutorial](https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types). – Pshemo Aug 26 '13 at 07:13
  • @user2716189 Also in [this answer](http://stackoverflow.com/a/5813490/1393766) author mention about using `listOfTestObject` while serializing and deserialiing collections of different objects. – Pshemo Aug 26 '13 at 07:17
  • @user2716189 `Then if at runtime, I dont know what aDog's class is` you always can use `getClass()` method to derermine real type of object. Java also have `instanceof` operator. – Pshemo Aug 26 '13 at 07:32
  • Thank you, that works, I parse the String to JsonObject and check its field value,then convert it to the right class – user2716189 Aug 26 '13 at 21:42