0

I am using JsonConverters in Newtonsoft.json. They will be providing me custom WriteJson / ReadJson code that I will use, so I need both the WriteJson / ReadJson to get triggered when a given objectType matches the converter.

One thing I need to do is convert the "null" keyword that shows up in the json to 0.

Below is a much simplified JsonConverter -- that all it does is attempt to change "null" to 0, (and anything else that's not null to 1). Unfortunately I have discovered that the WriteJson function never gets triggered when value == null.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;


namespace ConsoleApp1
{
  class Program
  {
    public class TestConverter : JsonConverter
    {
      public override bool CanConvert(Type objectType)
      {
        return objectType == typeof(B);
      }

      public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
      {
        return existingValue;
      }

      public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
      {
        /// This function never gets triggered when value is null
        if (value == null)
        {
          writer.WriteValue(0);
        }  
        else
        {
          writer.WriteValue(1);
        }
      }
    }

    public class B
    {
      public int C
      {
        get; set;
      }
    }

    public class A
    {
      public B B
      {
        get; set;
      } = null;
    }


    static void Main(string[] args)
    {
      var c = JsonConvert.SerializeObject(new A(), new JsonSerializerSettings()
      {
        Converters = new List<JsonConverter> { new TestConverter() }
      });

      Console.WriteLine(c);
    }
  }
}

Output:

{"B":null}

Expected Output:

{"B": 0}

Is there some setting or way to convert all output of "null" to "0" ?

Ilan Keshet
  • 176
  • 1
  • 8
  • Is this answer your question? https://stackoverflow.com/questions/16835188/replace-null-to-0-in-json-only-for-int-or-use-nullableint – Raju Melveetilpurayil Nov 11 '20 at 01:05
  • `WriteJson()` is never called for a null value, see [How to force JsonConverter.WriteJson() to be called for a null value](https://stackoverflow.com/q/52518593/3744182). – dbc Nov 11 '20 at 06:55
  • Does [How to force JsonConverter.WriteJson() to be called for a null value.](https://stackoverflow.com/q/52518593/3744182) answer your question? – dbc Nov 11 '20 at 14:52

1 Answers1

0

The converter class in the example only works when object with type of "B" is passed. Because in CanConvert method, you are checking if object is type of "B".

public override bool CanConvert(Type objectType)
{
    return objectType == typeof(B);
}

You should change typeof(B) to typeof(A), so converter will convert "A" class, which you are creating in the sample code:

var c = JsonConvert.SerializeObject(new A(), new JsonSerializerSettings()
{
    Converters = new List<JsonConverter> { new TestConverter() }
});

Now you're checking for the "A" object. To get "B" object in "A", you need to cast the object to "A", and then you can find out if "B" object in "A" is null or not.

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
   // cast object to A first, then get the B.
   B obj = ((A)value).B;

   // create our object first with WriteStartObject().
   writer.WriteStartObject();
   
   // write B's name in json, then it's value.
   writer.WritePropertyName(nameof(B));
   writer.WriteValue(obj != null ? 1 : 0); //ternary conditional that returns 0 for null, 1 for not-null.

   // end our object with WriteEndObject().
   writer.WriteEndObject();
}

Thus, result will look like:

{"B":0}