栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

我终于找到了答案。基本上,我不需要的

MediaTypeFormatter
东西不是为在MVC环境中使用而设计的,而是在ASP.NET Web
API中,这就是为什么我看不到那些引用和名称空间(顺便说一下,它们包含在
Microsoft.AspNet.WeApi
NuGet包中)的原因。

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

    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 onevalueProviderFactories.Factories.Add(new JsonNetValueProviderFactory());

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/375080.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号