Search code examples
c#jsonnulljson.netnull-string

JsonConvert.SerializeObject: Unexpected result when Serializing null value


In the line of code below, my string x ends up being an actual string "null" when clInitializer.AVOptions = null value:

string x = JsonConvert.SerializeObject(clInitializer.AVOptions, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});

As in actual word "null" and not a null value or perhaps {}. I am not sure this is expected behavior. Does anyone know how to make it not return the word "null", or do I have some fundamental misunderstanding on how JsonConvert works. Thank you in advance.


Solution

  • The NullValueHandling has to do with null values for a property and not the object it self.

    For example, if you have the below example:

    public class ExampleClass
    {
        public string NullProperty { get; set; }
    }
    

    And then you serialize it:

    var obj = new ExampleClass();
    var jsons = JsonConvert.SerializeObject(obj, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
    

    Then the NullProperty is ignored and you get {}.

    Edited

    The reason why "null" is returned is because the RFC for JSON (https://www.rfc-editor.org/rfc/rfc7159) explicitly states the following:

    A JSON value MUST be an object, array, number, or string, or one of
    the following three literal names:

    false null true

    The literal names MUST be lowercase. No other literal names are
    allowed.

    value = false / null / true / object / array / number / string

    false = %x66.61.6c.73.65 ; false

    null = %x6e.75.6c.6c ; null

    true = %x74.72.75.65 ; true

    Edited:

    I originally had a work around, but I removed it because I really think you should follow the RFC. The RFC clearly stated that a NULL object MUST be represented by a "null" so any work around is not a good idea.

    To stay with the RFC, I would store "null" or return "null" and not NULL. When you deserialize "null" it will return a NULL value.