user2716189
user2716189

Reputation: 63

Java JSON deserialize inheritance class

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?

Upvotes: 1

Views: 3972

Answers (1)

Pshemo
Pshemo

Reputation: 124215

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);

Upvotes: 1

Related Questions