简体   繁体   中英

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?

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

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