Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional output processing in JSON.NET

Having the following class:

class Test {
  [MyAttr]
  public string Name;
}

How can I extend JSON.NET if I need to trim values of all properties marked with MyAttr to specific length? Seems I can't do that in custom JsonConverter as I need access to MemberInfo representing the origin property.

like image 430
UserControl Avatar asked Dec 21 '25 16:12

UserControl


1 Answers

After deeper reading the documentation and source code it looks like contract resolver is the way to go:

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

As easy as pie!

like image 113
UserControl Avatar answered Dec 23 '25 04:12

UserControl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!