【问题标题】:Add Properties to anonymous type only if they are not null C#仅当属性不为空 C# 时才将属性添加到匿名类型
【发布时间】:2020-12-07 09:13:37
【问题描述】:

我有这个方法:

private string serializeResult(string errorCode = null, string parameter1 = null, string parameter2 = null, string context = null)
{
    return JsonConvert.SerializeObject(new
    {
        errorCode,
        parameter1,
        parameter2,
        context 
    });
}

现在如果 context、errorCode、parameter1 或 parameter2 为 null,我不希望为匿名类型添加它们。

如何在不测试所有选项的情况下做到这一点(我有更多参数,这是一个较小的问题)?

【问题讨论】:

标签: c# anonymous-types


【解决方案1】:

与其搞乱匿名类,不如提供自定义的 JSON 序列化设置:

return JsonConvert.SerializeObject(new
    {
        errorCode,
        parameter1,
        parameter2,
        context 
    }, new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore
    });

请注意,一般来说,有条件地从匿名类中删除值是没有意义的。假设您可以以某种方式做到这一点,如果您尝试访问会发生什么:

var anonClass = new
    {
        errorCode ?? removeIfNull, // fake syntax
        parameter1,
        parameter2,
        context 
    };
anonClass.errorCode // will this access succeed? We don't know until runtime!

【讨论】:

    【解决方案2】:

    您可以忽略来自序列化程序的null 值,如下所示。也请参考How to ignore a property in class if null, using json.net

    return JsonConvert.SerializeObject(new
    {
        errorCode,
        parameter1,
        parameter2,
        context 
    }, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
    

    【讨论】:

      猜你喜欢
      • 2010-09-19
      • 1970-01-01
      • 2012-03-10
      • 2016-08-29
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 2016-02-29
      相关资源
      最近更新 更多