小编典典

如何在MVC5项目中将Json.NET用于JSON模型绑定?

c#

我一直在互联网上寻找答案或示例,但找不到。我只是想更改默认的JSON序列化程序,该序列化程序用于在模型绑定到JSON.NET库时反序列化JSON。

我已经找到了这篇
SO帖子,但是到目前为止还无法实现,我什至看不到System.Net.Http.Formatters名称空间,也看不到GlobalConfiguration

我想念什么?

更新

我有一个ASP.NET MVC项目,它基本上是一个MVC3项目。目前,我的目标是.NET 4.5,并使用ASP.NET MVC 5和相关的NuGet软件包。

我没有看到System.Web.Http程序集,也没有看到任何类似的名称空间。在这种情况下,我想注入JSON.NET用作JSON类型的请求的默认模型绑定器。


阅读 512

收藏
2020-05-19

共1个答案

小编典典

我终于找到了答案。基本上,我不需要的MediaTypeFormatter东西不是为在MVC环境中使用而设计的,而是在ASP.NET Web
API中,这就是为什么我看不到那些引用和名称空间(顺便说一下,它们包含在Microsoft.AspNet.WeApiNuGet包中)的原因。

解决方案是使用自定义值提供程序工厂。这是所需的代码。

    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();
            // 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 (var entry in d)
                {
                    AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
                }
                return;
            }

            var l = value as IList;
            if (l != null)
            {
                for (var 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;
        }
    }

您可以在您的Application_Start方法中像这样使用它:

// remove default implementation    
ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());
// add our custom one
ValueProviderFactories.Factories.Add(new JsonNetValueProviderFactory());

是为我指出正确方向的文章,也是对价值提供者和模型绑定者的很好解释。

2020-05-19