Skip to content

JsonSerializer.Deserialize<T> throws NullReferenceException. JsonSerializer.Deserialize and JsonConvert.DeserializeObject works well #2492

@felipepessoto

Description

@felipepessoto

If JSON has a comment before a complex object, JsonSerializer throws a NullReferenceException

Expected behavior

No Exceptions or ArgumentException

Actual behavior

System.NullReferenceException: Object reference not set to an instance of an object.
   at Newtonsoft.Json.Linq.JTokenWriter.RemoveParent()
   at Newtonsoft.Json.Linq.JTokenWriter.WriteEnd(JsonToken token)
   at Newtonsoft.Json.JsonWriter.AutoCompleteClose(JsonContainerType type)
   at Newtonsoft.Json.JsonWriter.WriteEndObject()
   at Newtonsoft.Json.JsonWriter.WriteEnd(JsonContainerType type)
   at Newtonsoft.Json.JsonWriter.WriteEnd()
   at Newtonsoft.Json.JsonWriter.AutoCompleteAll()
   at Newtonsoft.Json.Linq.JTokenWriter.Close()
   at Newtonsoft.Json.JsonWriter.Dispose(Boolean disposing)
   at Newtonsoft.Json.JsonWriter.System.IDisposable.Dispose()
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateJToken(JsonReader reader, JsonContract contract)
   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[T](JsonReader reader)
   at TestJsonDeserialization.Program.Main(String[] args)

Steps to reproduce

string jsontext = @"{ ""ABC"": //DEF
{}}"; //NullReferenceException
//jsontext = "{ \"ABC\": /*DEF*/ {}}";  //NullReferenceException
//jsontext = "{ \"ABC\": /*DEF*/ 1}";//ArgumentException

using (var stringReader = new StringReader(jsontext))
using (var jsonReader = new JsonTextReader(stringReader))
{
    JsonSerializer serializer = JsonSerializer.Create();
    var x = serializer.Deserialize<JToken>(jsonReader);
}

JsonSerializer.Deserialize() and JsonConvert.DeserializeObject works fine.

Is it safe to replace

serializer.Deserialize<JToken>(jsonReader)

by

(JToken)serializer.Deserialize(jsonReader)

?

The behavior is exactly the same?

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions