JSON.NET serialization error in WebApi

I have a POCO class that inherits from several classes to give support for INotifyPropertyChanged and DataAnnotations. When WebApi returns a Court instance, the JSON.NET serializer throttles the delegate of the anonymous method to ModelPropertyAnnotationsValidation with an exception (showing the RAW response from Fiddler):

{"Message": "An error occurred.", "ExceptionMessage": "Type ObjectContent`1 could not serialize the response body for the content type 'application / json; encoding = UTF-8' " "ExceptionType.": "System.InvalidOperationException" "StackTrace": null, "InnerException": {"Message": "An error occurred.", "ExceptionMessage": "Error getting value from 'CS $ <> 9_CachedAnonymousMethodDelegate5' on 'Sample.Data.Models.Court'"" ExceptionType. ":" Newtonsoft.Json.JsonSerializationException "" StackTrace ":" in Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue (target object) \ r \ n in Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculProPro author, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract & memberContract, Object & memberValue) \ r \ n in Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject (JsonWriter author, object value, JsonObjectContracter contract, JsonObjectContracter member collectionContract, JsonProperty containerProperty) \ r \ n on Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue (JsonWriter author, object value, JsonContract valueContract,JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) \ r \ n on Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize (JsonWriter jsonWriter, object value) \ r \ n at Newtonsoft.Json.JsonSerializer.SerialWerereraloneraleralal r \ n at System.Net.Http.Formatting.JsonMediaTypeFormatter <. > C_DisplayClassd.b_c () \ r \ n in System.Threading.Tasks.TaskHelpers.RunSynchronously (action, CancellationToken token) "," InnerException ": {" Message ":" An error has occurred. ",value of the object) \ r \ n at System.Net.Http.Formatting.JsonMediaTypeFormatter <. > C_DisplayClassd.b_c () \ r \ n in System.Threading.Tasks.TaskHelpers.RunSynchronously (action, CancellationToken token) "," InnerException ": {" Message ":" An error has occurred. ",value of the object) \ r \ n at System.Net.Http.Formatting.JsonMediaTypeFormatter <. > C_DisplayClassd.b_c () \ r \ n in System.Threading.Tasks.TaskHelpers.RunSynchronously (action, CancellationToken token) "," InnerException ": {" Message ":" An error has occurred. ","ExceptionMessage": "Common Language Runtime detected the invalid Program" , "ExceptionType.": "System.InvalidProgramException" "StackTrace": "in GetCS $ <> 9_CachedAnonymousMethodDelegate5 (Object) \ r \ n in Newtonsoft.Json.Serialization.DynamicValueProvider. GetValue (Object Target) "}}}

Court class (edited for brevity):

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);
            }
        }
    }
}

Here is the inherited abstract class the problem is in (if I change getter to public string this[string columnName]to return an empty string, it works:

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
        }
    }
}

And for completeness, here is 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)));
            }
        }
    }
}

And the WebApi controller (which is very simple for you):

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};
        }

    }
}

How can I get what I suppose an anonymous delegate to go through serialization ... is ignored or otherwise?

+4
1

Json.NET ? (5.0.8), .

+4

All Articles