如何调试JSON序列化错误?

时间:2016-05-25 21:04:51

标签: .net serialization exception-handling json.net elmah

我有不一致但经常生成的以下异常:

System.Exception: Serialization error - One or more errors occurred., Unexpected character encountered while parsing value: <. Path '', line 0, position 0., System.AggregateException: One or more errors occurred. ---> Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
   at Newtonsoft.Json.JsonTextReader.ParseValue()
   at Newtonsoft.Json.JsonTextReader.Read()
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
   at Microsoft.AspNet.SignalR.Client.Transports.TransportHelper.b__1(String raw)
   at Microsoft.AspNet.SignalR.TaskAsyncHelper.<>c__DisplayClass19`2.b__17(Task`1 t)
   at Microsoft.AspNet.SignalR.TaskAsyncHelper.TaskRunners`2.<>c__DisplayClass42.b__41(Task`1 t)
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   **at Project.Services.NotificationService.SignalObjectToUser(Object data, String username, Boolean isTypingNotification)
---> (Inner Exception #0) Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.**
   at Newtonsoft.Json.JsonTextReader.ParseValue()
   at Newtonsoft.Json.JsonTextReader.Read()
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
   at Microsoft.AspNet.SignalR.Client.Transports.TransportHelper.b__1(String raw)
   at Microsoft.AspNet.SignalR.TaskAsyncHelper.<>c__DisplayClass19`2.b__17(Task`1 t)

重要的一点:

**at Project.Services.NotificationService.SignalObjectToUser(Object data, String username, Boolean isTypingNotification)
---> (Inner Exception #0) Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.**

我的代码:

private void SignalObjectToUser(object data, string username, bool isTypingNotification = false) {
        try {
            _hubConnection = new HubConnection(_baseUrl);
            _hubConnection.CookieContainer = new CookieContainer();
            _hubConnection.CookieContainer.Add(_cookie);
            _hubProxy = _hubConnection.CreateHubProxy("appHub");
            _hubConnection.Start().Wait();
            string serialized = null;
            try {
                List<string> errors = new List<string>();
                serialized = JsonConvert.SerializeObject(data, new JsonSerializerSettings() {
                    Error = delegate(object sender, ErrorEventArgs args) {
                        errors.Add(args.ErrorContext.Error.Message);
                        args.ErrorContext.Handled = true;
                        Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Delegated serialization error - " + args.ErrorContext.Error.Message));
                    }
                });
                _hubProxy.Invoke((isTypingNotification ? "SendTypingNotification" : "SendClientNotification"), serialized, username).Wait();
            }
            catch (Exception exception) {
                Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Serialization error - " + exception.Message + ", " + exception.InnerException.Message + ", " + exception.ToString()));
                throw new Exception("Messaging Error");
            }
        }
        catch (Exception e) {
            Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Serialization error - " + e.Message + ", " + e.InnerException.Message + ", " + e.ToString()));
            throw new Exception("Messaging Error");
        }
    }

我试图找出完全导致此问题的原因。我不知道哪个键/值对正在生成异常。我怎样才能在这里收集更具指导性的细节?

1 个答案:

答案 0 :(得分:1)

看起来你的端点(_baseUrl)应该返回JSON,但实际上返回XML或HTML。如果在请求_baseUrl时出现内部服务器错误,错误请求,未找到或类似错误,则会发生这种情况。如果您尝试在浏览器,邮递员或类似网站中请求URL,您可能会看到HTML响应和状态代码。