序列化自定义属性值

时间:2016-10-24 05:38:20

标签: c#-4.0 json.net custom-attributes

鉴于以下课程:

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

有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

如果我理解你的问题,你想序列化应用于类的属性的属性列表吗?

如果是这样,您可以使用辅助方法来执行此操作:

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属性,并且属性名称不是驼峰式的。要解决此问题,您需要使用自定义合约解析程序:

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

演示小提琴:https://dotnetfiddle.net/2R5Zyi