我有一个带有对象值属性的C#类。我将此属性设置为枚举值,序列化为Json,然后反序列化回对象。
如何将对象的属性值反序列化回enum?
即,给定:
public class Foo
{
public object Value { get; set; }
}
public enum SmallNumbers { One, Two, Three }
如何让这个测试通过?
[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);
}
答案 0 :(得分:1)
可以为这种特殊情况编写一个转换器,但是如果你有很多像Object这样的'Value'属性我将没有用处,因为没有什么可以告诉转换每个Object的类型。检查下面的代码&amp;在你的机器上运行测试。
using System;
using Newtonsoft.Json;
using NUnit.Framework;
class StackOverflowIssue7801000
{
public enum SmallNumbers { One, Two, Three }
public class Foo
{
public object Value { get; set; }
}
class ObjectToSmallNumbersConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// Not required for deserialization
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return (SmallNumbers)Convert.ToInt32(reader.Value);
}
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(object));
}
}
[Test]
public void an_object_property_set_to_an_enum_can_be_serialised()
{
var settings = new JsonSerializerSettings {
TypeNameHandling = TypeNameHandling.All
};
var json = JsonConvert.SerializeObject(new Foo { Value = SmallNumbers.Three }, Formatting.None, settings);
settings.Converters.Add(new ObjectToSmallNumbersConverter());
var foo = JsonConvert.DeserializeObject<Foo>(json, settings);
Assert.That(foo.Value is SmallNumbers);
}
}