'export and import gson - Failed to invoke public ) with no args

i'm learning how to convert array to json file and import that array with using gson. I have abstract class Shape;

public abstract class Shape {
private Type typeOfShape;

public abstract double countArea();

public abstract double countCircuit();
}

and classes Circle, Rectangle, Square which extends Shape, for example Rectangle

public class Rectangle extends Shape {
private double a;
private double b;

public Rectangle(Type type, int a, int b) {
    super(type);
    this.a = a;
    this.b = b;
}

@Override
public double countArea() {
    return a * b;
}

@Override
public double countCircuit() {
    return a * 2 + b * 2;
}

and 2 methods:

public static List<Shape> importShapeListFromJsonWithGson(String path) throws IOException {
    Type listType = new TypeToken<List<Shape>>() {}.getType();
    Gson gson = new GsonBuilder().create();
    Reader reader = new FileReader(path);
    List<Shape> result = gson.fromJson(reader, listType);
    return result;
}

public static void exportShapeListToJsonWithGson(List<Shape> list, String path) throws IOException {
    Writer writer = new FileWriter(path);
    Gson gson = new GsonBuilder().create();
    gson.toJson(list, writer);
    writer.close();
}

But i'm getting Exception in thread "main" java.lang.RuntimeException: Failed to invoke public Shape() with no args . Is the problem that, i'm using abstract class? I tried to remove abstract from Shape, and then compile one more time, but i was getting only list with shapes, without for example "a" or "b", only, with type.



Solution 1:[1]

Old question, but maybe helpful: I believe this is an indication from Gson that Shape (or an descendent of Shape) needs a default constructor.

I moved to lombok a bit ago and have a few classes where I've forgot to annotate my class with @NoArgsConstructor. As a result, when deserializing some complex object graphs, Gson blows up with an error just like you've received.

Hope you figured it out anyways ;)

Solution 2:[2]

Maybe Circle, Rectangle and Square need to get a no arg constructor.

Ok, I was a bit too hasty with my answer. In the meantime I tried to solve the task myself, but unfortunately had no success either. But the following SO shows how to solve basically the serialization of a polymorphic list:

https://stackoverflow.com/a/19600090/3439487

Maybe this will be helpful for you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gary Teichrow
Solution 2