I've been scouring the internet about how to use JSON with libgdx, specifically loading and saving objects, but all I've been able to find is tutorials dealing with 1 object only. In my case I am going to be dealing with lots of objects inside lots of other objects.

To put this into perspective, lets say I have a World class.

Within the World class there is a list of Level classes.

Within each Level class there is an array of Tile classes.

Within each Tile class there is a TopTile class and a BotTile class.

The BotTile and TopTile classes contain Integers and Strings and things.

Within each Level class there are also Entity lists

Each Entity has an Inventory which has Items

As you can see, there are a lot of classes, and within these classes there are more classes. Do I have to write a saving wrapper for every single class? I understand I could just save the whole World class, and to my understanding this would just pile everything in to one file, but there is a lot of garbage that doesn't need to be saved in all the other classes. How should I go about saving my World class?

To clarify, when I mentioned a saving wrapper, I mean a set of methods in object X which save and load X using only necessary parameters, thus getting rid of all the garbage. But, I have so many objects that might be saved that writing wrappers for each of these seems like a lot.

Another thing is, in the case of an Inventory class containing Items, I would only want to save the contents of the inventory, not the actual Item classes because nothing is changing about each Item. Though would saving the Inventory not save all of the items it contains as well? I find this all a bit confusing. What is being saved? what is not being saved? This is all using the libGDX JSON parser, of objects I am assuming.

Any suggestions would be greatly appreciated.

有帮助吗?

解决方案

I'm doing exactly this in my libGDX game. You do it like this:

{
    "object_name": "basic_left_gun",
    "object_type" : "player_ship_component",
    "object_subtype" : "player_ship_left_weapon",
    "subtype_properties" : 
        {
            "shot_name" : "basic_shot"
        },
    "is_animated": false,
    "is_dual_state": false,
    "is_destructible": true,
    "hitpoints": 16,
    "second_state_name": "",
}

So have a look at the "subtype_properties" field. It has another JSON object inside of it. So when I serialize and query the JSON object in java, when I do json.get("subtype_properties"), I actually just get another JSON object. From there I can query and get the attributes.

Theoretically, you could do this forever and ever. Although my approach has been to have basic definitions stores in JSONs for each object, and then link their properties together using the nested JSON objects as above, or define unique properties using the same approach.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top