Change default null value in JSON.NET

Is there a way to set what the default representation for null values ​​should be in Json.NET ? More specifically, null values ​​inside an array.

Given the class

public class Test
{
    public object[] data = new object[3] { 1, null, "a" };
}

Then do it

Test t = new Test();
string json = JsonConvert.SerializeObject(t);

gives

{"data":[1,null,"a"]}

Is it possible to do it like this?

{"data":[1,,"a"]}

Without using string.Replace.

0
source share
1 answer

Figured it out. I had to implement a custom JsonConverter. As others have said, this will not lead to valid / standard Json.

public class ObjectCollectionConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType ==  typeof(object[]);
    }

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

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        object[] collection = (object[])value;
        writer.WriteStartArray();
        foreach (var item in collection)
        {
            if (item == null)
            {
                writer.WriteRawValue(""); // This procudes "nothing"
            }
            else
            {
                writer.WriteValue(item);
            }
        }
        writer.WriteEndArray();
    }
}

Use it like this:

Test t = new Test();
string json = JsonConvert.SerializeObject(t, new ObjectCollectionConverter());
0
source

Source: https://habr.com/ru/post/1628380/


All Articles