Change default null value in JSON.NET

2019-06-09 13:10发布

Is there some 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 doing this

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

Gives

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

Is it possible to make it look like this?

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

Without using string.Replace.

1条回答
萌系小妹纸
2楼-- · 2019-06-09 13:51

Figured it out. I had to implement a custom JsonConverter. As others mentioned this will not produce 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());
查看更多
登录 后发表回答