using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace Question42274847
public class ReturnNullConverter<T> : JsonConverter
public override bool CanConvert(Type objectType)
return typeof(T).IsAssignableFrom(objectType);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
if (reader.TokenType == JsonToken.Null)
var contract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(objectType);
existingValue = existingValue ?? contract.DefaultCreator();
serializer.Populate(reader, existingValue);
.All(p => object.ReferenceEquals(p.ValueProvider.GetValue(existingValue), null)))
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
throw new NotImplementedException();
public class CustomResponse
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string Message { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string Details { get; set; }
public class CustomResponseSubClass : CustomResponse
public int SomeInt { get; set; }
internal static void Test()
Test<CustomResponse>("{}", true);
Test<CustomResponse>("{Message: null}", true);
Test<CustomResponse>("{Details: null}", true);
Test<CustomResponse>(@"{""DocumentId"":""123321"", ""DocumentNumber"":""ABC123""}", true);
Test<CustomResponse>("{Message: \"a\"}", false);
Test<CustomResponse>("{Details: \"a\", Message: null}", false);
Test<CustomResponseSubClass>("{}", false);
Console.WriteLine("All tests passed");
static void Test<T>(string jsonString, bool shouldBeNull) where T : CustomResponse
var settings = new JsonSerializerSettings
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore,
Converters = { new ReturnNullConverter<CustomResponse>() },
var customResponse = JsonConvert.DeserializeObject<T>(jsonString, settings);
Assert.IsTrue((customResponse == null) == shouldBeNull);
Console.WriteLine("Correctly deserialized \"{0}\" to {1}", jsonString, shouldBeNull ? "null" : "a non-null object of type " + typeof(T).Name);
public class AssertionFailedException : System.Exception
public AssertionFailedException() : base() { }
public AssertionFailedException(string s) : base(s) { }
public static class Assert
public static void IsTrue(bool value)
throw new AssertionFailedException("failed");
public static void Main()
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Question42274847.TestClass.Test();