3

具有以下课程:

class Test {
  [MyAttr]
  public string Name;
}

如果我需要将所有标记为特定长度的属性的值修剪为特定长度,我该如何扩展JSON.NETMyAttr?似乎我不能在自定义中这样做,JsonConverter因为我需要访问MemberInfo表示 origin 属性。

4

1 回答 1

3

在深入阅读文档和源代码之后,看起来合同解析器是要走的路:

public class MyCustomConverter : JsonConverter
{
    public override bool CanConvert(Type objectType) {
        return true;
    }

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

    public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) {
        if (value == null) {
            writer.WriteNull();
            return;
        }
        string str = value.ToString().Substring(1, 2);
        writer.WriteValue(str);
    }
}

public class MaskContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) {
        JsonProperty property = base.CreateProperty(member, memberSerialization);
        if (member.CustomAttributes.Any(x => typeof(MyAttr).IsAssignableFrom(x.AttributeType)))
            property.Converter = new MyCustomConverter();
        return property;
    }
}

像馅饼一样容易!

于 2012-11-05T13:48:26.857 回答