如何序列化和反序列化在Json.Net中设置为enum值的对象属性



我有一个带有对象值属性的c#类。我将此属性设置为enum值,序列化为Json,然后反序列化回对象。

如何使对象的属性值反序列化回枚举?

即给定:

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);
   }

可以为这种特殊情况编写转换器,但如果您有许多属性,如'Value'类型的对象,我将不会有帮助,因为没有什么可以告诉转换每个对象的类型。检查下面的代码&在您的机器上运行测试。

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);
    }
}

相关内容

  • 没有找到相关文章