在JSON.NET更改默认空值 [英] Change default null value in JSON.NET

查看:117
本文介绍了在JSON.NET更改默认空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一些方法来设置为空值默认表示应该在 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.

由于类

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"]}

如果不使用与string.replace。

Without using string.Replace.

推荐答案

想通了。我不得不实现自定义JsonConverter。
正如其他人提到这不会产生有效的/标准的Json

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

使用像这样

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

这篇关于在JSON.NET更改默认空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆