【问题标题】:Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'System.Runtime.Serialization.ISafeSerializationData'无法将类型为“Newtonsoft.Json.Linq.JObject”的对象转换为类型“System.Runtime.Serialization.ISafeSerializationData”
【发布时间】:2014-07-09 09:21:11
【问题描述】:

我在尝试反序列化 Web api 调用时遇到以下异常 - 消息模糊不清,所以我无法理解发生了什么 - 此转换在其他情况下有效,不确定这里出了什么问题:

例外:

  InnerException: System.Reflection.TargetInvocationException
   _HResult=-2146232828
   _message=Exception has been thrown by the target of an invocation.
   HResult=-2146232828
   IsTransient=false
   Message=Exception has been thrown by the target of an invocation.
   Source=mscorlib
   StackTrace:
        at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
        at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
        at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
        at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
        at Newtonsoft.Json.Serialization.JsonContract.<>c__DisplayClass1.<CreateSerializationCallback>b__0(Object o, StreamingContext context)
        at Newtonsoft.Json.Serialization.JsonContract.InvokeOnDeserialized(Object o, StreamingContext context)
        at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.OnDeserialized(JsonReader reader, JsonContract contract, Object value)
        at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateISerializable(JsonReader reader, JsonISerializableContract contract, JsonProperty member, String id)
        at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
        at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
        at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
        at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
        at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
        at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
        at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
        at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
        at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
        at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, Encoding effectiveEncoding, IFormatterLogger formatterLogger)
        at System.Net.Http.Formatting.JsonMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, Encoding effectiveEncoding, IFormatterLogger formatterLogger)
        at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
     --- End of stack trace from previous location where exception was thrown ---
        at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
        at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
        at System.Net.Http.HttpContentExtensions.<ReadAsAsyncCore>d__0`1.MoveNext()
   InnerException: System.InvalidCastException
        _HResult=-2147467262
        _message=Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'System.Runtime.Serialization.ISafeSerializationData'.
        HResult=-2147467262
        IsTransient=false
        Message=Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'System.Runtime.Serialization.ISafeSerializationData'.
        Source=mscorlib
        StackTrace:
             at System.Runtime.Serialization.SafeSerializationManager.CompleteDeserialization(Object deserializedObject)
             at System.Exception.OnDeserialized(StreamingContext context)
        InnerException: 

我的代码:

public SensoriaApiResult<T> PostSensoriaApiResult(object body)
    {
        HttpClient client = SetupClient();

        HttpResponseMessage response;
        response = client.PostAsJsonAsync(url, body).Result;

        SensoriaApiResult<T> result = response.Content.ReadAsAsync<SensoriaApiResult<T>>().Result;
        return result;
    }

Json 返回:

{"StatusCode":500,"APIResult":null,"HttpError":{"Message":"Sensoria API internal error","SensoriaApiErrorCode":983041},"Exception":{"ClassName":"System.Data.Entity.Infrastructure.DbUpdateException","Message":"An error occurred while updating the entries. See the inner exception for details.","Data":{},"InnerException":{"ClassName":"System.Data.Entity.Core.UpdateException","Message":"An error occurred while updating the entries. See the inner exception for details.","Data":{},"InnerException":{"Errors":[{"source":".Net SqlClient Data Provider","number":547,"state":0,"errorClass":16,"server":".","message":"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_UserBase.ClosetItems_Catalog.Products\". The conflict occurred in database \"Sensoria.Knowledge.Database\", table \"dbo.Catalog.Products\", column 'ProductId'.","procedure":"","lineNumber":1,"win32ErrorCode":0},{"source":".Net SqlClient Data Provider","number":3621,"state":0,"errorClass":0,"server":".","message":"The statement has been terminated.","procedure":"","lineNumber":1,"win32ErrorCode":0}],"ClientConnectionId":"7b976c29-59ff-491c-a3aa-01750e17cb36","ClassName":"System.Data.SqlClient.SqlException","Message":"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_UserBase.ClosetItems_Catalog.Products\". The conflict occurred in database \"Sensoria.Knowledge.Database\", table \"dbo.Catalog.Products\", column 'ProductId'.\r\nThe statement has been terminated.","Data":{"HelpLink.ProdName":"Microsoft SQL Server","HelpLink.ProdVer":"11.00.3128","HelpLink.EvtSrc":"MSSQLServer","HelpLink.EvtID":"547","HelpLink.BaseHelpUrl":"http://go.microsoft.com/fwlink","HelpLink.LinkId":"20476"},"InnerException":null,"HelpURL":null,"StackTraceString":"   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)\r\n   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)\r\n   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()\r\n   at System.Data.SqlClient.SqlDataReader.get_MetaData()\r\n   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)\r\n   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)\r\n   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c__DisplayClassb.<Reader>b__8()\r\n   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed)\r\n   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)\r\n   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n   at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)\r\n   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()","RemoteStackTraceString":null,"RemoteStackIndex":0,"ExceptionMethod":"8\nOnError\nSystem.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\nSystem.Data.SqlClient.SqlConnection\nVoid OnError(System.Data.SqlClient.SqlException, Boolean, System.Action`1[System.Action])","HResult":-2146232060,"Source":".Net SqlClient Data Provider","WatsonBuckets":null},"HelpURL":null,"StackTraceString":"   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()\r\n   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)\r\n   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction, Boolean throwOnClosedConnection)\r\n   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update(Boolean throwOnClosedConnection)\r\n   at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__33()\r\n   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)\r\n   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy)\r\n   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass28.<SaveChanges>b__25()\r\n   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)\r\n   at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)\r\n   at System.Data.Entity.Internal.InternalContext.SaveChanges()","RemoteStackTraceString":null,"RemoteStackIndex":0,"ExceptionMethod":"8\nUpdate\nEntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\nSystem.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator\nInt32 Update()","HResult":-2146233087,"Source":"EntityFramework","WatsonBuckets":null},"HelpURL":null,"StackTraceString":"   at Sensoria.Models.ShoeClosetModel.CreateClosetModelForUser(Int32 userId, ShoeClosetItem newClosetItem) in c:\\Users\\maurgi\\Source\\Hg\\sensoria-main\\Source\\Web\\Sensoria.Models\\ShoeClosetModel.cs:line 225\r\n   at Sensoria.Models.ShoeClosetModel.CreateClosetItem(Int32 userID, ShoeClosetItem newClosetItem) in c:\\Users\\maurgi\\Source\\Hg\\sensoria-main\\Source\\Web\\Sensoria.Models\\ShoeClosetModel.cs:line 76\r\n   at Sensoria.Api.Controllers.ShoeClosetController.AddNewShoe(Int32 userId, ShoeClosetItem sItem) in c:\\Users\\maurgi\\Source\\Hg\\sensoria-main\\Source\\Web\\Sensoria.Api\\Controllers\\ShoeClosetController.cs:line 79","RemoteStackTraceString":null,"RemoteStackIndex":0,"ExceptionMethod":"8\nCreateClosetModelForUser\nSensoria.Models, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\nSensoria.Models.ShoeClosetModel\nSensoria.Models.ShoeClosetModel CreateClosetModelForUser(Int32, Sensoria.Api.Core.Models.ShoeClosetItem)","HResult":-2146233087,"Source":"Sensoria.Models","WatsonBuckets":null,"SafeSerializationManager":{"m_serializedStates":[{"<InvolvesIndependentAssociations>k__BackingField":false}]},"CLR_SafeSerializationManager_RealType":"System.Data.Entity.Infrastructure.DbUpdateException, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"},"ModelState":null}

Generic APIResult 类定义:

public class SensoriaApiResult<T>
{
    /// <summary>
    /// The 
    /// </summary>
    [DataMember]
    public HttpStatusCode StatusCode;
    [DataMember]
    public T APIResult;
    [DataMember]
    public HttpError HttpError;
    [DataMember]
    public Exception Exception;
    [DataMember]
    public ModelStateDictionary ModelState;

    ...

}

【问题讨论】:

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


【解决方案1】:

如果你观察返回的json,代表序列化的异常,有趣的部分就在这里:

..."InnerException":{"Errors":[{"source":".Net SqlClient Data Provider","number":547,"state":0,"errorClass":16,"server" :".","message":"INSERT 语句与 FOREIGN KEY 约束 \"FK_UserBase.ClosetItems_Catalog.Products\" 冲突。冲突发生在数据库 \"Sensoria.Knowledge.Database\",表 \"dbo.Catalog .Products\", column 'ProductId'.","procedure":"","lineNumber":1,"win32ErrorCode":0},{"source":".Net SqlClient Data Provider","number":3621 ,"state":0,"errorClass":0,"server":".","message":"语句已终止。","procedure":"","lineNumber":1,"win32ErrorCode" :0}],"ClientConnectionId":"7b976c29-59ff-491c-a3aa-01750e17cb36","ClassName":"System.Data.SqlClient.SqlException","Message":"INSERT 语句与 FOREIGN 冲突KEY 约束 \"FK_UserBase.ClosetItems_Catalog.Products\"。冲突发生在数据库 \"Sensoria.Knowledge.Database\"、表 \"dbo.Catalog.Products\"、列 'ProductId' 中。\r\ n 声明已终止。","Data":{"HelpLink.ProdName":"Microsoft SQL ...

即这条语句:

INSERT 语句与 FOREIGN KEY 约束冲突 \"FK_UserBase.ClosetItems_Catalog.Products\"。冲突发生在数据库 \"Sensoria.Knowledge.Database\",表 \"dbo.Catalog.Products\",列 'ProductId'**

所以我建议观察你正在接收和传递的参数body 的值:PostSensoriaApiResult(object body)。可能有一些ProductId 不存在(通常是0,即任何int 属性的默认值)

【讨论】:

  • 感谢您的回复!我知道这是错误 - 但我想将此信息转换为我的类型:具有 Exception 属性的 SensoriaApiResult 以便客户端可以检查它。不幸的是,反序列化/强制转换失败,客户端留下了一个难以理解的异常.. -
  • 我想说,问题是:您应该首先阅读响应。将其反序列化为某个对象,捕获该过程的任何异常。实施决策树 - 如果响应包含错误而不是预期结果。接下来,有了这些信息,您应该手动(在代码中)用处理后的信息填写您的SensoriaApiResult。然后这些将被正确序列化。我会说...把它分成步骤。不要一次完成所有工作
【解决方案2】:

由于这个问题已经将近 2 年了,我非常怀疑我对原始发帖人有什么帮助,但是对于任何在谷歌上搜索这个错误的人来说,这是因为许多实体数据框架异常没有实现序列化构造函数,而是依赖于SerializeObjectState 事件(System.Net.Http.HttpRequestException 也是如此,这恰好是过去几个小时一直让 me 适应的小虫子)。 JSON.NET 不能正确处理这种情况,如this 错误报告中所述。

【讨论】:

  • 多么节省时间。非常感谢。
【解决方案3】:

当我尝试反序列化具有HttpRequestException 类型的内部异常的异常(我已序列化)时遇到了这个问题。 此异常无法反序列化,因为它没有实现 GetObjectData

我的解决方案是在序列化之前删除 HttpRequestException 实例。

【讨论】:

    【解决方案4】:

    关于HttpRequestException 的序列化/反序列化,这个可怕的黑客解决了我的问题:

    string myJson = JsonConvert.SerializeObject(myObject).Replace("\"SafeSerializationManager\":", "\"_SafeSerializationManager\":");
    

    【讨论】:

    • 这对我也有用。似乎是我现在能找到的唯一方法。当你的异常有异常时,你就知道你有麻烦了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 2020-03-17
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多