序列化自定义属性值

Serialize Custom Attribute Values

给出以下 class:

public class PayrollReport
{
    [UiGridColumn(Name = "fullName",Visible = false,Width = "90")]
    public string FullName { get; set; }
    [UiGridColumn(Name = "weekStart", CellFilter = "date")]
    public DateTime WeekStart { get; set; }
}

还有这个自定义属性

[AttributeUsage(AttributeTargets.All)]
public class UiGridColumn : Attribute
{
    public string CellFilter { get; set; }
    public string DisplayName { get; set; }
    public string Name { get; set; }
    public bool Visible { get; set; }
    public string Width { get; set; }
}

我想为每个仅包含提供值的字段创建一个 List<UiGridColumn>(我不希望跳过的属性为 null)。

是否可以创建一个 List<UiGridColumn>,其中每个 List 项都只有提供的值? (我担心这是不可能的,但我想我会问)如果是这样,怎么办?

如果没有,我的第二选择是像这样的字符串数组:

[{"name":"fullName","visible":false,"width":"90"},{"name":"weekStart","cellFilter":"date"}]

我不想遍历每个 propertyattribute 以及 argument 来手动构建所需的 JSON 字符串,但我无法做到找到一个简单的方法来做。

public List<Object> GetUiGridColumnDef(string className)
{
    Assembly assembly = typeof(DynamicReportService).Assembly;
    var type = assembly.GetType(className);
    var properties = type.GetProperties();

    var columnDefs = new List<object>();
    foreach (var property in properties)
    {
        var column = new Dictionary<string, Object>();
        var attributes = property.CustomAttributes;
        foreach (var attribute in attributes)
        {
            if (attribute.AttributeType.Name != typeof(UiGridColumn).Name || attribute.NamedArguments == null)
                    continue;
            foreach (var argument in attribute.NamedArguments)
            {
                column.Add(argument.MemberName, argument.TypedValue.Value);
            }
        }
        columnDefs.Add(column);
    }
    return columnDefs;
}

有更好的方法吗?

如果我对你的问题的理解正确,你想序列化应用于 class 上的属性的属性列表?

如果是这样,您可以创建一个辅助方法来执行此操作:

public static string SerializeAppliedPropertyAttributes<T>(Type targetClass) where T : Attribute
{
    var attributes = targetClass.GetProperties()
                                .SelectMany(p => p.GetCustomAttributes<T>())
                                .ToList();

    JsonSerializerSettings settings = new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore,
        Formatting = Formatting.Indented
    };

    return JsonConvert.SerializeObject(attributes, settings);
}

然后像这样使用它:

string json = SerializeAppliedPropertyAttributes<UiGridColumn>(typeof(PayrollReport));

你最终会得到这个输出,它与你正在寻找的非常接近:

[
  {
    "Name": "fullName",
    "Visible": false,
    "Width": "90",
    "TypeId": "UiGridColumn, JsonTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
  },
  {
    "CellFilter": "date",
    "Name": "weekStart",
    "Visible": false,
    "TypeId": "UiGridColumn, JsonTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
  }
]

您会注意到 TypeId 属性 来自基础 Attribute class 被包括在内,并且 属性 名称不是驼峰式。要解决此问题,您需要使用自定义合同解析器:

public class SuppressAttributeTypeIdResolver : CamelCasePropertyNamesContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty prop = base.CreateProperty(member, memberSerialization);
        if (member.DeclaringType == typeof(Attribute) && member.Name == "TypeId")
        {
            prop.ShouldSerialize = obj => false;
        }
        return prop;
    }
}

将解析器添加到辅助方法中的序列化设置,您应该可以开始了:

    JsonSerializerSettings settings = new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore,
        ContractResolver = new SuppressAttributeTypeIdResolver(),
        Formatting = Formatting.Indented
    };

现在输出应该如下所示:

[
  {
    "name": "fullName",
    "visible": false,
    "width": "90"
  },
  {
    "cellFilter": "date",
    "name": "weekStart",
    "visible": false
  }
]

演示 fiddle:https://dotnetfiddle.net/2R5Zyi