Change default null value in JSON.NET

不羁的心 提交于 2019-12-13 12:45:59

问题


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:


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


来源:https://stackoverflow.com/questions/19747914/change-default-null-value-in-json-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!