What's wrong with this deserialization from a JSON file to objects using Gson?

那年仲夏 提交于 2020-01-11 14:38:07

问题


So I have the following super class:

public class Location {

    private String name;
    private double[] coordinates;
    private String description;

}

And the following subclasses:

public class Monument extends Location {

    private String architect;
    private short inauguration;

}

public class Restaurant extends Location {

    private String[] characteristics;
}

public class Hotel extends Location {

    private short stars;
}

The JSON file I'm trying to deserialize is an array of Locations where each location can be a Monument, Hotel or Restaurant depending of the fields of the location. For example, if a location in the JSON has a field named 'stars' we will know that object is from the class Hotel, inherited from the class Location.

I was trying to deserialize the file using the following code:

public class DataModel {

    private Location[] locations;

    public void loadData () {

        JsonReader reader;

        try {

            reader = new JsonReader(new FileReader("data/localitzacions.json"));

            RuntimeTypeAdapterFactory<Location> runtimeTypeAdapterFactory = RuntimeTypeAdapterFactory.of(Location.class, "locations")
                    .registerSubtype(Hotel.class, "stars")
                    .registerSubtype(Monument.class, "name")
                    .registerSubtype(Restaurant.class, "characteristics");

            Gson gson = new GsonBuilder().registerTypeAdapterFactory(runtimeTypeAdapterFactory).create();

            locations = gson.fromJson(reader, Location.class);
            System.out.println("Hecho");

        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "El fichero JSON no se ha encontrado");
        }
    }
}

But the output is a bunch of errors:

Exception in thread "main" com.google.gson.JsonSyntaxException: 
java.lang.IllegalStateException
at com.google.gson.Gson.fromJson(Gson.java:944)
at models.DataModel.loadData(DataModel.java:32)
at utils.Logic.loadData(Logic.java:161)
at com.company.Main.main(Main.java:12)
Caused by: java.lang.IllegalStateException
at com.google.gson.JsonArray.getAsString(JsonArray.java:226)
at extra.RuntimeTypeAdapterFactory$1.read(RuntimeTypeAdapterFactory.java:236)
at com.google.gson.TypeAdapter$1.read(TypeAdapter.java:199)
at com.google.gson.Gson.fromJson(Gson.java:932)
... 3 more

Here is the JSON I'm trying to deserialize:

What am I doing wrong?

来源:https://stackoverflow.com/questions/59593828/whats-wrong-with-this-deserialization-from-a-json-file-to-objects-using-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!