首页 > 解决方案 > ssis - 美化 json 字符串

问题描述

我正在尝试美化一个 json 字符串,我通过以下方式获得它:

 string json = JsonConvert.SerializeObject(Row, Formatting.Indented);

似乎它工作得很好,但它包括 _IsNull 字段,我怎样才能避免这种情况?

"ID": 35208,
"ID_IsNull": false,
"name": "SONIA",
"name_IsNull": false

我会:

"ID": 35208,
"name": "SONIA"

标签: c#jsonssis

解决方案


我认为最好的方法是实现一个合同解析器并自动忽略所有具有 _IsNull 名称后缀的属性:

    private class IgnoredNullIndicationPropertiesJsonContractResolver : DefaultContractResolver
    {
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            var property = base.CreateProperty(member, memberSerialization);

            if (property.PropertyName.EndsWith("_IsNull"))
            {
                property.Ignored = true;
            }

            return property;
        }
    }

然后,您可以使用 JSON 序列化程序应用它,如下所示:

var serializerSettings = new JsonSerializerSettings
                    {
                        ContractResolver = new IgnoredNullIndicationPropertiesJsonContractResolver(),
                    };

                    string json = JsonConvert.SerializeObject(Row, Formatting.Indented, serializerSettings);

推荐阅读