From b47f7440d19f56478d0f7b87bc9319ea43174e71 Mon Sep 17 00:00:00 2001 From: Mikko Rantanen Date: Sat, 5 Nov 2016 15:07:05 +0200 Subject: [PATCH] Fix null reference error when deserializing bytes If the JSON contained empty object "{}" for a byte[] property, the `JsonReader` ended up trying to read the object content despite the fact that the content didn't exist. This caused a null reference exception. The fix ensures the value exists before trying to read it. If the value doesn't exist, the execution ends up in "Unexpected token" exception with way more informative error message. --- .../JsonTextReaderTests/ExceptionHandlingTests.cs | 8 ++++++++ Src/Newtonsoft.Json/JsonReader.cs | 4 ++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ExceptionHandlingTests.cs b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ExceptionHandlingTests.cs index d8ca6e6f..41e5b75e 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ExceptionHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ExceptionHandlingTests.cs @@ -384,6 +384,14 @@ namespace Newtonsoft.Json.Tests.JsonTextReaderTests ExceptionAssert.Throws(() => { reader.ReadAsBytes(); }, "Unexpected end when reading JSON. Path '', line 1, position 1."); } + [Test] + public void ReadBytesEmptyWrappedObject() + { + JsonTextReader reader = new JsonTextReader(new StringReader(@"{}")); + + ExceptionAssert.Throws(() => { reader.ReadAsBytes(); }, "Error reading bytes. Unexpected token: StartObject. Path '', line 1, position 2." ); + } + [Test] public void ReadIntegerWithError() { diff --git a/Src/Newtonsoft.Json/JsonReader.cs b/Src/Newtonsoft.Json/JsonReader.cs index d0d319aa..f761b746 100644 --- a/Src/Newtonsoft.Json/JsonReader.cs +++ b/Src/Newtonsoft.Json/JsonReader.cs @@ -904,7 +904,7 @@ namespace Newtonsoft.Json internal void ReadIntoWrappedTypeObject() { ReaderReadAndAssert(); - if (Value.ToString() == JsonTypeReflector.TypePropertyName) + if (Value != null && Value.ToString() == JsonTypeReflector.TypePropertyName) { ReaderReadAndAssert(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) @@ -1182,4 +1182,4 @@ namespace Newtonsoft.Json return t; } } -} \ No newline at end of file +}