I have a unity project. Using the stock json tools at my disposal, i'm trying to deserialize an enum that uses bit flags (ie something like)
[Flags]
enum Terrain
{
NORMAL = 0,
FOREST = 1,
SWAMP = 2,
CAVE = 4
}
In json it's something like CityTerrain: "FOREST", however it seems that the deserialization doesn't like human readable string enums (it wants an integer i assume) which is especially troubling for me in the case of bit flags when i want to be able to combine flags, ie. FOREST|CAVE.
XML handled bitflag enums fine out of the box. Why does json, the superior format, seem to struggle with it so badly? Should i be making an enum wrapper for handling the deserialization of this? No matter what i do, i feel like my solution will be clunky and i will dislike it.
Ultimately it needs to be human readable and i won't accept a "solution" where my bitflag enum has to be represented as 5 in json. The entire point of this exercise is that it needs to be human readable but still deserializable.
For
Newtonsoft.Jsonyou can use a
StringEnumConverterand pass it along intoand (actually optional apparently)
in my test for deserializing it seems to also work with only
For
System.Text.Jsonyou can use the equivalent
JsonStringEnumConverterand pass it via the options like e.g.and
.Net Fiddle for both above
Note (also applies to
JsonUtilitybelow): Both basically go throughToStringandEnum.Parseso in the json it will read e.g.if for some reason you really want
FOREST|SWAMPinstead you will have to implement your own customJsonConverter(Newtonsoft) or accordinglyJsonConverter(System.Text.Json).Basically using the same and do something like (pseudo code)
and
For built-in
JsonUtilityafaik there is unfortunately nothing similar. You instead have to overwrite the serialization of the entire class like e.g.
NOTE:
Terrainand shall be json serialized