问题
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