I have a C# class with an object valued property. I am setting this property to an enum value , serialising to Json and then deserialising back to the object.
How can I make the object’s property value deserialise back to the enum?
That is, given:
public class Foo
{
public object Value { get; set; }
}
public enum SmallNumbers { One, Two, Three }
How can I make this test pass?
[Test]
public void an_object_property_set_to_an_enum_can_be_serialised()
{
var settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto
};
var json = JsonConvert.SerializeObject(
new Foo {Value = SmallNumbers.One},
Formatting.None,
settings);
var foo = JsonConvert.DeserializeObject<Foo>(json, settings);
Assert.That(foo.Value is SmallNumbers);
}
It’s possible to write a converter for this special case but I won’t be helpful if you have many properties like ‘Value’ of type Object because there’s nothing to tell to which type to convert each Object. Check the code below & run the test on your machine.