C# 在序列化之前将特定对象转换为字典

C# 在序列化之前将特定对象转换为字典,c#,json.net,C#,Json.net,我正在使用Json.NET序列化数据字段的验证数据。在.NET端,验证数据是ValidationAttribute对象的列表。但是,我希望以如下特殊形式序列化它们: [ { Type: 'Required', ErrorMessage: '{FieldName} is required' }, { Type: 'RegularExpression', Pattern: '^\d+$', ErrorMessage: '...' ] 在理想的解决方案中,我可以在序列化之前截取对象,并创建相

我正在使用
Json.NET
序列化数据字段的验证数据。在.NET端,验证数据是
ValidationAttribute
对象的列表。但是,我希望以如下特殊形式序列化它们:

[
  { Type: 'Required', ErrorMessage: '{FieldName} is required' },
  { Type: 'RegularExpression', Pattern: '^\d+$', ErrorMessage: '...'
]
在理想的解决方案中,我可以在序列化之前截取对象,并创建相应的
字典
对象来进行序列化,而不是原始对象


这个场景有什么解决方案吗?

您可以实现自己的
JsonConverter
类,并根据需要转换集合

您只需要创建类并从
JsonConverter

public class YourSerializer : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(YourClassName).IsAssignableFrom(objectType);
    }
}
然后,您需要装饰您的类,该类将使用属性序列化(看起来它不是您想要的)

或者,传递序列化程序的实例以序列化方法:

string json = JsonConvert.SerializeObject(sourceObj, Formatting.Indented, new YourSerializer(typeof(yourClassName)));
以下是一些链接:


希望,这会有所帮助。

事实上,我在某种程度上了解JSONConverter,但不认为这项任务可以用它们轻松解决。我使用了一个定制的JsonConverter,并根据需要填充了一个JObject。非常感谢。
string json = JsonConvert.SerializeObject(sourceObj, Formatting.Indented, new YourSerializer(typeof(yourClassName)));