枚举不会从非字符串值序列化

时间:2014-08-15 18:43:25

标签: c# asp.net json serialization enums

我在此ScheduleDatePeriod课程中将此属性EditEventScheduleSettingsModel作为枚举。我将jSON序列化为javascript中的页面,使其成为属性Period: 1。当我将此作为Period: 1提交给服务器时,枚举始终为null。这是为什么?

属性

public ScheduleDatePeriod? Period { get; set; }

动作

 [HttpPost]
        public virtual ActionResult Grid(int eventId, EditEventScheduleSettingsModel settings)
        {

JSON

{
   Period: 1
}

枚举

[DataContract(Namespace = "")]
public enum ScheduleDatePeriod
{
    [EnumMember(Value = "0"), Display(Name = "None")]
    None = 0,
    [EnumMember(Value = "1"), Display(Name = "Day")]
    Day = 1,
    [EnumMember(Value = "2"), Display(Name = "Week")]
    Week = 2
}

ValueProviderFactory

    public class JsonNetValueProviderFactory : ValueProviderFactory
    {
        public override IValueProvider GetValueProvider(ControllerContext controllerContext)
        {
            // first make sure we have a valid context
            if (controllerContext == null)
                throw new ArgumentNullException("controllerContext");

            // now make sure we are dealing with a json request
            if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
                return null;

            // get a generic stream reader (get reader for the http stream)
            var streamReader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
            // convert stream reader to a JSON Text Reader
            var jsonReader = new JsonTextReader(streamReader);
            // tell JSON to read
            if (!jsonReader.Read())
                return null;

            // make a new Json serializer
            var jsonSerializer = new JsonSerializer();
            jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            // add the dyamic object converter to our serializer
            jsonSerializer.Converters.Add(new ExpandoObjectConverter());

            // use JSON.NET to deserialize object to a dynamic (expando) object
            Object jsonObject;
            // if we start with a "[", treat this as an array
            if (jsonReader.TokenType == JsonToken.StartArray)
                jsonObject = jsonSerializer.Deserialize<List<ExpandoObject>>(jsonReader);
            else
                jsonObject = jsonSerializer.Deserialize<ExpandoObject>(jsonReader);

            // create a backing store to hold all properties for this deserialization
            var backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
            // add all properties to this backing store
            AddToBackingStore(backingStore, String.Empty, jsonObject);
            // return the object in a dictionary value provider so the MVC understands it
            return new DictionaryValueProvider<object>(backingStore, CultureInfo.CurrentCulture);
        }

        private static void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value)
        {
            var d = value as IDictionary<string, object>;
            if (d != null)
            {
                foreach (KeyValuePair<string, object> entry in d)
                {
                    AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
                }
                return;
            }

            var l = value as IList;
            if (l != null)
            {
                for (int i = 0; i < l.Count; i++)
                {
                    AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);
                }
                return;
            }

            // primitive
            backingStore[prefix] = value;
        }

        private static string MakeArrayKey(string prefix, int index)
        {
            return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
        }

        private static string MakePropertyKey(string prefix, string propertyName)
        {
            return (String.IsNullOrEmpty(prefix)) ? propertyName : prefix + "." + propertyName;
        }
    }

Global.asax中

ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());
ValueProviderFactories.Factories.Add(new JsonNetValueProviderFactory());

2 个答案:

答案 0 :(得分:0)

我对JsonNetValueProviderFactory进行了一些测试,我认为我找到了问题的原因。

以下行将“Period”值解析为long而不是int。枚举的值是一个int,导致转换为枚举失败。

jsonObject = jsonSerializer.Deserialize<ExpandoObject>(jsonReader);

我无法找到一个好的解决方案,但这些是解决方法

  • 将句点作为字符串值传递
  • 使用默认的JsonValueProviderFactory

答案 1 :(得分:0)

我不确定您是否提供了您使用的完整JSON,但我使用下一个JSON测试了您的示例,并且enum已成功反序列化(在fiddler中测试)。

{
    "eventId": 10,
    "settings": 
       {
        "Period" : 2
       }
}

请注意,您应该使用JSON中的“设置”来匹配方法中参数的名称。