Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7054389
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T03:37:14+00:00 2026-05-28T03:37:14+00:00

When serializing arbitrary data via JSON.NET, any property that is null is written to

  • 0

When serializing arbitrary data via JSON.NET, any property that is null is written to the JSON as

“propertyName” : null

This is correct, of course.

However I have a requirement to automatically translate all nulls into the default empty value, e.g. null strings should become String.Empty, null int?s should become 0, null bool?s should be false, and so on.

NullValueHandling is not helpful, since I dont want to Ignore nulls, but neither do I want to Include them (Hmm, new feature?).

So I turned to implementing a custom JsonConverter.
While the implementation itself was a breeze, unfortunately this still didnt work – CanConvert() is never called for a property that has a null value, and therefore WriteJson() is not called either. Apparently nulls are automatically serialized directly into null, without the custom pipeline.

For example, here is a sample of a custom converter for null strings:

public class StringConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(string).IsAssignableFrom(objectType);
    }

    ...
    public override void WriteJson(JsonWriter writer, 
                object value, 
                JsonSerializer serializer)
    {
        string strValue = value as string;

        if (strValue == null)
        {
            writer.WriteValue(String.Empty);
        }
        else
        {
            writer.WriteValue(strValue);
        }
    }
}

Stepping through this in the debugger, I noted that neither of these methods are called for properties that have a null value.

Delving into JSON.NET’s sourcecode, I found that (apparently, I didnt go into a lot of depth) there is a special case checking for nulls, and explictly calling .WriteNull().

For what it’s worth, I did try implementing a custom JsonTextWriter and overriding the default .WriteNull() implementation…

public class NullJsonWriter : JsonTextWriter
{
    ... 
    public override void WriteNull()
    {
        this.WriteValue(String.Empty);
    }
}

However, this can’t work well, since the WriteNull() method knows nothing about the underlying datatype. So sure, I can output "" for any null, but that doesnt work well for e.g. int, bool, etc.

So, my question – short of converting the entire data structure manually, is there any solution or workaround for this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T03:37:15+00:00Added an answer on May 28, 2026 at 3:37 am

    Okay, I think I’ve come up with a solution (my first solution wasn’t right at all, but then again I was on the train). You need to create a special contract resolver and a custom ValueProvider for Nullable types. Consider this:

    public class NullableValueProvider : IValueProvider
    {
        private readonly object _defaultValue;
        private readonly IValueProvider _underlyingValueProvider;
    
    
        public NullableValueProvider(MemberInfo memberInfo, Type underlyingType)
        {
            _underlyingValueProvider = new DynamicValueProvider(memberInfo);
            _defaultValue = Activator.CreateInstance(underlyingType);
        }
    
        public void SetValue(object target, object value)
        {
            _underlyingValueProvider.SetValue(target, value);
        }
    
        public object GetValue(object target)
        {
            return _underlyingValueProvider.GetValue(target) ?? _defaultValue;
        }
    }
    
    public class SpecialContractResolver : DefaultContractResolver
    {
        protected override IValueProvider CreateMemberValueProvider(MemberInfo member)
        {
            if(member.MemberType == MemberTypes.Property)
            {
                var pi = (PropertyInfo) member;
                if (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof (Nullable<>))
                {
                    return new NullableValueProvider(member, pi.PropertyType.GetGenericArguments().First());
                }
            }
            else if(member.MemberType == MemberTypes.Field)
            {
                var fi = (FieldInfo) member;
                if(fi.FieldType.IsGenericType && fi.FieldType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    return new NullableValueProvider(member, fi.FieldType.GetGenericArguments().First());
            }
    
            return base.CreateMemberValueProvider(member);
        }
    }
    

    Then I tested it using:

    class Foo
    {
        public int? Int { get; set; }
        public bool? Boolean { get; set; }
        public int? IntField;
    }
    

    And the following case:

    [TestFixture]
    public class Tests
    {
        [Test]
        public void Test()
        {
            var foo = new Foo();
    
            var settings = new JsonSerializerSettings { ContractResolver = new SpecialContractResolver() };
    
            Assert.AreEqual(
                JsonConvert.SerializeObject(foo, Formatting.None, settings), 
                "{\"IntField\":0,\"Int\":0,\"Boolean\":false}");
        }
    }
    

    Hopefully this helps a bit…

    Edit – Better identification of the a Nullable<> type

    Edit – Added support for fields as well as properties, also piggy-backing on top of the normal DynamicValueProvider to do most of the work, with updated test

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm serializing an object that contains HTML data in a String Property. Dim Formatter
I am serializing to a json object using: public static string ToJson(this object obj)
I am serializing a generic dictionary in VB.net and I am very surprised that
I'm aware that serializing is used to convert data types into a storable format,
In ASP.NET WebForms I want to pass arbitrary data from server to client and
Simply put serializing data in the application/json; charset=utf-8 format misbehaves in MVC3 (and possibly
To aid in serializing to JSON, I commonly build a class that inherits from
When serializing, I would like to serialize an object only once, then any references
I'm serializing an object in a C# VS2003 / .Net 1.1 application. I need
I'm serializing class which contains DateTime property. public DateTime? Delivered { get; set; }

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.