JSON.NET序列化失败

时间:2013-03-01 12:44:28

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

我有一个LINQ-to-SQL对象,可以毫无问题地序列化为XML。我可以调用Newtonsoft.Json.JsonConvert.SerializeObject(),我得到JSON结果。当我在WebAPI中传递与对象相同的结果时,我得到一个错误(见下文)。我构建了一个跟踪编写器来捕获null内部异常路径,如果路径是'',我不知道如何确定导致错误的项目?

20130301122959: Started serializing AnvilDB.Partner. Path ''.
20130301122959: Error serializing AnvilDB.Partner. An item with the same key has already been added. Path ''.
Error: An item with the same key has already been added.
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
   at System.Web.Http.Metadata.Providers.AssociatedMetadataProvider`1.CreateTypeInformation(Type type)
   at System.Web.Http.Metadata.Providers.AssociatedMetadataProvider`1.GetTypeInformation(Type type)
   at System.Web.Http.Metadata.Providers.AssociatedMetadataProvider`1.GetMetadataForProperty(Func`1 modelAccessor, Type containerType, String propertyName)
   at System.Web.Http.Validation.ModelValidationRequiredMemberSelector.IsRequiredMember(MemberInfo member)
   at System.Net.Http.Formatting.JsonContractResolver.ConfigureProperty(MemberInfo member, JsonProperty property)
   at System.Net.Http.Formatting.JsonContractResolver.CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
   at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateProperties(Type type, MemberSerialization memberSerialization)
   at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateObjectContract(Type objectType)
   at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract(Type objectType)
   at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract(Type type)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
20130301123002: Started serializing System.Web.Http.HttpError. Path ''.
20130301123002: Started serializing System.Web.Http.HttpError. Path 'InnerException'.
20130301123002: Finished serializing System.Web.Http.HttpError. Path 'InnerException'.
20130301123002: Finished serializing System.Web.Http.HttpError. Path ''.

2 个答案:

答案 0 :(得分:6)

挖掘我发现我可以为序列化程序设置错误处理程序,然后检查ErrorContext.Member值。这指向了XElement类型的属性。进一步搜索发现这是一个已知/报告的错误,但尚未修复;见https://github.com/JamesNK/Newtonsoft.Json/issues/53

摘要:如果您的XElement属性具有空值,则JSON.NET将失败。

以下是我为诊断根本原因而添加的内容:

    base.Configuration.Formatters.JsonFormatter.SerializerSettings.Error = (sender, args) =>
    {
        string e = string.Format("{0}: {1}", args.ErrorContext.Member, args.ErrorContext.Path, args.ErrorContext.Error.Message);
        myTracer.Trace(System.Diagnostics.TraceLevel.Error, e, args.ErrorContext.Error);
    };

myTracer是一个简单的文件跟踪编写器。


<强>更新

我现在找到了这个bug的解决方案。

WebAPI用于序列化JSON对象的类不是直接来自JSON.NET,而是设置为JsonContractResolver的实例,该实例位于System.Net.Http.Formatting中。幸运的是,这是开源的,所以你可以在这里看到当前的版本:

http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/4764b0111b91#src/System.Net.Http.Formatting/Formatting/JsonContractResolver.cs

我将这个确切的代码复制到我自己的类中,并使用我自己的类替换JSON.NET中的契约解析器,使用此代码(未更改)并修复了错误。由此我得出结论,当前发布的WebAPI版本(System.Net.Http.Formatting版本4.0.20710.0)中存在错误,下一个版本可能会解决此问题。

如果像我这样你现在需要解决它,请按以下步骤操作:

  1. 使用JsonContractResolver.cs代码
  2. 创建自己的合约解析程序类
  3. 更改启动配置以覆盖ContractResolver设置:
  4. 样品:

    var settings = System.Web.Http.GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings; 
    // create formatter 
    var formatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); 
    settings.ContractResolver = new MyJsonContractResolver(formatter);
    

    这应该有所帮助。

答案 1 :(得分:0)

这看起来像是Web API中的一个错误。我建议在这里提交一个关于它的错误:

http://aspnetwebstack.codeplex.com/workitem/list/basic

与此同时,我认为您可以通过设置如下配置来解决此问题:

config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();