0
\$\begingroup\$

I'm trying to save the player's inventory as a JSON data but I'm having a problem. I have a class Sword which extends an abstract class Weapon which extends another abstract class called Item. This is what JSON file looks like with the Sword and Armor objects in it:

[
    {
        "category": {
            "type": "Weapon",
            "subtype": "Sword"
        },
        "id": 0,
        "value": 1,
        "name": "Wooden Sword",
        "description": "Sword made out of wood",
        "slug": "wooden_sword",
        "stats": {
            "wear": 100,
            "damage": 5
        }
    },
    {
        "category": {
            "type": "Armor",
            "subtype": "Helmet"
        },
        "id": 1337,
        "value": 1,
        "name": "Steel Helmet",
        "description": "Whatever...",
        "slug": "steel_helmet",
        "stats": {
            "wear": 100,
            "defence": 5,
            "vitality": 3,
            "dexterity": -1
        }
    }
]

How can I parse these objects into their respective C# objects, putting the first entry into a Sword object and the second one into a Helmet object. There will be other types of objects in there too, so it's not limited on these two.

\$\endgroup\$
  • 3
    \$\begingroup\$ "I have a class Sword which extends abstract class Weapon which extends another abstract class Item." Unrelated to your issue, but... what will you do when you'll want to use a Shield (presumably an 'Armor') as a weapon ("Shield bash")? What will happen when you'll want to use your sword as a defense ("Parry")? Take a look at Composition over inheritance before going too deep into your objects hierarchy. \$\endgroup\$ – Alexandre Vaillancourt Aug 11 '17 at 12:56
  • 2
    \$\begingroup\$ That's a really good advice, thank you. I'll certainly look into it. \$\endgroup\$ – Irakli Chkuaseli Aug 11 '17 at 13:11
1
\$\begingroup\$

Directly converting these objects using JSONUtil won't work in this case.

What you could do instead is parse it into an intermediate data-structure first. Create a struct which directly mimics the structure of that JSON code (with a category variable which is another struct with the fields type and subtype).

You can then use the data in that structure to instantiate the actual objects of the correct types.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.