在序列化期间添加新属性,在反序列化期间删除属性

时间:2018-09-04 15:02:39

标签: c# attributes json.net

假设我上了这样的课:

[Version(123)]
public class Test
{

}

如何为生成的json添加属性“版本”:123?

我一直在玩自定义ContractResolver,但没有成功。.

protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        var properties = base.CreateProperties(type, memberSerialization);

        var attributes = type.GetCustomAttributes(false);

        VersionAttribute attribute = (VersionAttribute)attributes.FirstOrDefault(att => att is VersionAttribute);
        if (attribute != null)
        {
            JsonProperty versionProperty = new JsonProperty();
            versionProperty.ValueProvider = new ValueProvider(attribute);
            versionProperty.PropertyType = typeof(int);
            versionProperty.PropertyName = "Version";
            versionProperty.DefaultValue = 0;
            properties.Add(versionProperty);
        }

        return properties;
    }

0 个答案:

没有答案