Custom JSON.NET converter: serialize object based on property value

Sometimes we need inspect content of an object and then decide if whole object will be serialized. Example: we're serailizing List, and have to skip specific users based on the value of some property.

Custom JsonConverter to the rescue:


public class CustomConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var user = value as User;

        if(user == null) return;

        if (user.SomePropertyValue == "allowed")
        {
            var t = JToken.FromObject(value);
            t.WriteTo(writer);
        }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException("Converter usage just is for writing");
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(User);
    }
}


// usage:

var jsonSettings = new JsonSerializerSettings();
jsonSettings.Converters.Add(new CustomConverter());

var payload = JsonConvert.SerializeObject(users, jsonSettings);

results matching ""

    No results matching ""