JSON

在MVC中使用Json.Net序列化和反序列化Json对象(2)

字号+ 作者:H5之家 来源:H5之家 2015-11-12 15:04 我要评论( )

2,在初始化MVC时替换掉默认的JsonValueProviderFactory。 在Global.asax的Application_Start时,写入以下代码: ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfTypeJsonValueProvi

2,在初始化MVC时替换掉默认的JsonValueProviderFactory。
在Global.asax的Application_Start时,写入以下代码:

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

3,建立新的ModelBinder,命名为JsonNetModelBinder。

namespace MvcJsonNet { using System; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Web.Mvc; using Newtonsoft.Json; public class JsonNetModelBinder : DefaultModelBinder { BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) { Debug.WriteLine("BindProperty"); if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json.net", StringComparison .InvariantCultureIgnoreCase)) { //根据Content type来判断,只有json.net这种content type的才会使用该ModelBinder,否则使用默认的Binder base.BindProperty(controllerContext, bindingContext, propertyDescriptor); return; } // need to skip properties that aren't part of the request, else we might hit a StackOverflowException string name = propertyDescriptor.Name; foreach (object attribute in propertyDescriptor.Attributes) { if (attribute is JsonPropertyAttribute) { var jp = attribute as JsonPropertyAttribute; name = jp.PropertyName; } } string fullPropertyKey = CreateSubPropertyName(bindingContext.ModelName, name); if (!bindingContext.ValueProvider.ContainsPrefix(fullPropertyKey)) { return; } // call into the property's model binder IModelBinder propertyBinder = Binders.GetBinder(propertyDescriptor.PropertyType); object originalPropertyValue = propertyDescriptor.GetValue(bindingContext.Model); ModelMetadata propertyMetadata = bindingContext.PropertyMetadata[propertyDescriptor.Name]; propertyMetadata.Model = originalPropertyValue; var innerBindingContext = new ModelBindingContext { ModelMetadata = propertyMetadata, ModelName = fullPropertyKey, ModelState = bindingContext.ModelState, ValueProvider = bindingContext.ValueProvider }; object newPropertyValue = GetPropertyValue(controllerContext, innerBindingContext, propertyDescriptor, propertyBinder); propertyMetadata.Model = newPropertyValue; // validation ModelState modelState = bindingContext.ModelState[fullPropertyKey]; if (modelState == null || modelState.Errors.Count == 0) { if (OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, newPropertyValue)) { SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue); OnPropertyValidated(controllerContext, bindingContext, propertyDescriptor, newPropertyValue); } } else { SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue); // Convert FormatExceptions (type conversion failures) into InvalidValue messages foreach ( ModelError error in modelState.Errors.Where(err => String.IsNullOrEmpty(err.ErrorMessage) && err.Exception != null) .ToList()) { for (Exception exception = error.Exception; exception != null; exception = exception.InnerException) { if (exception is FormatException) { string displayName = propertyMetadata.GetDisplayName(); string errorMessageTemplate = "The value '{0}' is not valid for {1}."; string errorMessage = String.Format(CultureInfo.CurrentCulture, errorMessageTemplate, modelState.Value.AttemptedValue, displayName); modelState.Errors.Remove(error); modelState.Errors.Add(errorMessage); break; } } } } } } }

4,建立一个VModel的基类,为该基类添加Attribute,然后在Global中添加Model和Binder的映射。

[ModelBinder(typeof (JsonNetModelBinder))] VEntity { Id { get; set; } }

Global.asax中Application_Start添加代码:

ModelBinders.Binders.Add(typeof(VEntity), new JsonNetModelBinder());

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • 浅谈使用PHP开发微信支付的流程

    浅谈使用PHP开发微信支付的流程

    2016-02-13 15:00

  • Unity3D脚本:Unity3D使用LitJson解析服务器上的JSON

    Unity3D脚本:Unity3D使用LitJson解析服务器上的JSON

    2016-01-31 10:32

  • WebServices中使用JSON

    WebServices中使用JSON

    2016-01-24 18:13

  • 如何使用SBJson

    如何使用SBJson

    2016-01-23 08:01

网友点评