简体   繁体   中英

Change default null value in JSON.NET

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.

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM