mifriis / edge-of-kuiper

Textbased space rpg somewhat based on real science
Other
7 stars 3 forks source link

Newtonsoft deserializes Enums wrong? #28

Closed mifriis closed 3 years ago

mifriis commented 3 years ago

I have stumbled upon an odd behaviour. When saving a solar system/captain it contains a number of locations. These locations have an Enum that is their type, called SatteliteType: https://github.com/mifriis/edge-of-kuiper/blob/mifriis/moremining/kuiper-game/Domain/Location.cs#L45

When looking at the Save and Load functionality, i can't really spot anything that could be the problem: https://github.com/mifriis/edge-of-kuiper/blob/mifriis/moremining/kuiper-game/Systems/SaveLoad.cs

And debug inspecting the "solar system" just before serialization shows all locations having the right type.

Opening the save file, they still have the correct type:

"Locations": [
        {
            "$id": "2",
            "Name": "Earth",
            "Sattelites": [
                {
                    "$id": "3",
                    "Name": "Luna",
                    "Sattelites": [],
                    "OrbitalRadius": 384400,
                    "SatteliteType": 1
                },
                {
                    "$id": "4",
                    "Name": "Asteroid",
                    "Sattelites": [],
                    "OrbitalRadius": 20000,
                    "SatteliteType": 2
                }
            ],
            "OrbitalRadius": 150740000,
            "SatteliteType": 0
        },
        {
            "$ref": "3"
        }
    ],

But upon Deserialization, they are suddenly the "Planet" enum.

I have created an integration test that shows this behaviour here: https://github.com/mifriis/edge-of-kuiper/blob/mifriis/moremining/kuiper-tests/SaveLoadShould.cs#L30

But i simple cannot figure out why it's doing that. Perhaps you could take a look?

Should be as simple as grabbing my branch and running the test to show it failing.

kristianholmsejersen commented 3 years ago

Decorate the SatteliteType enum type with a [JsonConverter(typeof(StringEnumConverter))] attribute

mifriis commented 3 years ago

Decorate the SatteliteType enum type with a [JsonConverter(typeof(StringEnumConverter))] attribute

That fixed it, but I have a sneaky suspicioun it's also because i keep forgetting the ctor params need to match the fields in the JSON file too.