나는 POCO 클래스를 가지고 있는데, POCO 클래스는 INotifyPropertyChanged 및 DataAnnotations 지원을 위해 몇 가지 클래스를 상속합니다.WebApi의 JSON.NET 직렬화 오류
{ "메시지": WebApi 법정의 인스턴스를 리턴 할 때, JSON.NET 시리얼 라이저 (피들러의 RAW 대응을 도시)를 제외한 ModelPropertyAnnotationsValidation의 익명 방식 대리자 초크 "오류가 발생했습니다. ", "ExceptionMessage ":" 'ObjectContent`1'형식이 콘텐츠 형식 'application/json; charset = utf-8' "에 대한 응답 본문을 serialize하지 못했습니다.", "ExceptionType": "System.InvalidOperationException ","StackTrace ": null,"InnerException ": {"메시지 ":" 오류가 발생했습니다. ", "ExceptionMessage ":" 에서 값을 가져 오는 중 오류 발생. 'CS $' 에'> 9_ CachedAnonymousMethodDelegate5 Sample.Data.Models.Court ' ","예외 유형. ":"Newtonsoft.Json.JsonSerializationException ","스택 트레이스 ":" Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue에서 ( 대상 오브젝트) \ R \ n Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues (JsonWriter 라이터 개체 값 JsonContainerContract 계약 JsonProperty 부재 JsonProperty 속성 JsonContract &에서 memberContract은 개체 & memberValue) \ R \ n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject (JsonWriter 작가, 개체 va 루, JsonObjectContract 계약 JsonProperty 부재 JsonContainerContract collectionContract, JsonProperty containerProperty) \ R \ n Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue (JsonWriter 라이터 개체 값 JsonContract valueContract, JsonProperty 부재 JsonContainerContract containerContract, JsonProperty에서 containerProperty) \ R \ n Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize (JsonWriter jsonWriter 오브젝트 값)에서 \ R \ n Newtonsoft.Json.JsonSerializer.SerializeInternal (JsonWriter jsonWriter 오브젝트 값)에서 \ R \ n은 입니다. System.Net.Http.Formatting.JsonMediaTypeFormatter. <> C _DisplayClassd.b_ C() \ R \ n System.Threading.Tasks.TaskHelpers.RunSynchronously (액션 액션 CancellationToken 토큰)에서 는 ""의 InnerException "{"메시지 ":"오류 을 갖는다 발생했습니다 ", 는"ExceptionMessage가. "". 공용 언어 런타임이 무효 프로그램을 발견 ","예외 유형 ":"System.InvalidProgramException ","스택 트레이스를 ":" 에서 GetCS $ <> 9 _CachedAnonymousMethodDelegate5 (객체) \ 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]
에 게터로를 변경하는 경우 빈 문자열을 반환, 그것은 작동 :
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};
}
}
}
어떻게 내가 익명의 대리인이 직렬화를 통과 ... 무시하거나 가정 무엇을 얻을 수 있나요?
4.5.11은 WebApi와 함께 설치되었으며 NuGet을 통해 업데이트를 확인하지는 않았습니다. 이제는 5.0.8에서 작동하므로 절대적으로 문제가되었습니다. 고마워, 제임스 ... 대답과 Json.NET. :) –