WebApi中的JSON.NET序列化错误

时间:2013-12-11 02:18:30

标签: c# json serialization asp.net-web-api json.net

我有一个POCO类,它继承了几个类,为它提供了INotifyPropertyChanged和DataAnnotations支持。当WebApi返回Court的实例时,JSON.NET序列化程序会对ModelPropertyAnnotationsValidation中的匿名方法委托进行扼流,并带有异常(显示来自Fiddler的RAW响应):

  

{“消息”:“发生错误。”,“ExceptionMessage”:“   'ObjectContent`1'类型无法序列化响应主体   内容类型'application / json;   字符集= UTF-8' “” ExceptionType。 “:” System.InvalidOperationException “ ”堆栈跟踪“:空 ”的InnerException“:{ ”消息“:” 一个   错误已经发生。“,”ExceptionMessage“:”从中获取值时出错   'CS $<> 9_ CachedAnonymousMethodDelegate5'开启   'Sample.Data.Models.Court' “” ExceptionType。 “:” Newtonsoft.Json.JsonSerializationException “ ”堆栈跟踪“:”   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object   目标)\ r \ n at   Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter   writer,Object value,JsonContainerContract contract,JsonProperty   成员,JsonProperty财产,JsonContract& memberContract,Object&   memberValue)\ r \ n at   Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter   writer,Object value,JsonObjectContract契约,JsonProperty   成员,JsonContainerContract collectionContract,JsonProperty   containerProperty)\ r \ n at   Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter   writer,Object value,JsonContract valueContract,JsonProperty成员,   JsonContainerContract containerContract,JsonProperty   containerProperty)\ r \ n at   Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter   jsonWriter,Object value)\ r \ n at   Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter   jsonWriter,Object value)\ r \ n at   System.Net.Http.Formatting.JsonMediaTypeFormatter<。&以及c _DisplayClassd.b_ C(个)\ r \ n   在System.Threading.Tasks.TaskHelpers.RunSynchronously(动作,   CancellationToken token)“,”InnerException“:{”Message“:”错误有   发生了。“,”ExceptionMessage“:”公共语言运行时检测到了   无效   程序 “下,” ExceptionType。 “:” System.InvalidProgramException “ ”堆栈跟踪“:”   at GetCS $<> 9 _CachedAnonymousMethodDelegate5(Object)\ r \ n at   Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(对象   目标)“}}}

法庭类(为简洁而编辑):

using System;
using System.Collections.Generic;
using Sample.Data.Models.Infrastructure;

namespace Sample.Data.Models
{
    [Serializable]
    public partial class Court : ModelPropertyAnnotationsValidation
    {
        public Court()
        {
        }

        private int _courtID;
        public int CourtID
        {
            get { return _courtID; }
            set 
            { 
                _courtID = value; 
                OnPropertyChanged(() => CourtID);
            }
        }
    }
}

这是问题所在的继承抽象类(如果我更改public string this[string columnName]上的getter以返回空字符串,它可以工作:

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace Sample.Data.Models.Infrastructure
{
    public abstract class ModelPropertyAnnotationsValidation : ModelBase
    {
        public string this[string columnName]
        {
            get
            {
                var type = GetType();
                var modelProperties = TypeDescriptor.GetProperties(type).Cast<PropertyDescriptor>();

                var enumerable = from modelProperty in modelProperties.Where(modelProp => modelProp.Name == columnName)
                                 from attribute in modelProperty.Attributes.OfType<ValidationAttribute>().Where(attribute => !attribute.IsValid(modelProperty.GetValue(this)))
                                 select attribute.ErrorMessage;
                return enumerable.FirstOrDefault();
            }
            private set { ; } //http://developerstreasure.blogspot.com/2010/05/systemruntimeserializationinvaliddataco.html
        }

        public string Error
        {
            get { return null; }
            private set { ; } //http://developerstreasure.blogspot.com/2010/05/systemruntimeserializationinvaliddataco.html
        }


        public virtual bool IsValid
        {
            get
            {
                var validationContext = new ValidationContext(this, null, null);
                var valid = Validator.TryValidateObject(this, validationContext, null, validateAllProperties: true);
                return valid;
            }
            private set { ; } //http://developerstreasure.blogspot.com/2010/05/systemruntimeserializationinvaliddataco.html
        }
    }
}

为了完整起见,这里是ModelBase:

using System;
using System.ComponentModel;
using System.Linq.Expressions;

namespace Sample.Data.Models.Infrastructure
{
    public abstract class ModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(Expression<Func<object>> property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(BindingHelper.Name(property)));
            }
        }
    }
}

WebApi控制器(为此目的非常简单):

using System.Web.Http;
using Sample.Data.Models;

namespace Sample.Services.Api.Controllers
{
    public class CourtsController : ApiController
    {
        // GET api/values
        public Court Get()
        {
            return new Court {Abbreviation = "TEST", FullName = "Test Court", Active = true};
        }

    }
}

我怎样才能得到一个匿名代表通过序列化...忽略或其他?

1 个答案:

答案 0 :(得分:4)

您使用的是什么版本的Json.NET?如果您没有使用最新版本(5.0.8),请升级到它并再次运行您的应用程序。