pg-robban
pg-robban

Reputation: 1435

How should I implement this method?

Suppose I have a superclass Entity and some subclasses Creature,Heroes etc. I have all the data for the subclasses in JSON files which contain arrays that represent each subclass, for example the file json/creatures/a.json represent all the Creatures that are of type A. I'm parsing the files using gson. Here's what an example file might look like:

[
    {
        "name":         "Pikeman",
        "attack":       4,
        "defence":      5,
        // ...
    },
    {
        "name":         "Halberdier",
        "attack":       6,
        "defence":      5,
    }
]

Now I was thinking that I could make a method in Entity which parses a given JSON file and returns an instance of one of Entity's subclasses with the data it parsed. If the file only contained one entity, I could do something like

public static Entity parseFromJson(File file, Class<? extends Entity> c) {
    return gson.fromJson(new FileReader(file), c);
}

But now it gets complicated: The files contain arrays of the subclasses. Should I pass Class<? extends Entity[]> and make the return type Entity[] instead? If so, then where and how should I access a single element of that array? Or should I rather have just one creature per file and send the name as a string instead?

Upvotes: 1

Views: 129

Answers (1)

Johan Sj&#246;berg
Johan Sj&#246;berg

Reputation: 49197

You could try

public static <T extends Entity> T parseFromJSON(File file, Class<T> clazz) {
    return clazz.cast(gson.FromJson(new FileReader(file), clazz));
}

public static <T extends Entity> T[] parseFromJSONArray(File file, Class<T[]> clazz) {
    return clazz.cast(gson.FromJson(new FileReader(file), clazz));
}

Which you could use something like (given that gson accepts it)

Foo foo = parseFromJSON(file, Foo.class);
Foo[] foos = parseFromJSONArray(file, Foo[].class);

Upvotes: 2

Related Questions