user2774635
user2774635

Reputation: 85

Json.NET: How to prevent a type from being serialized

When trying to serialize a list of objects of polymorphic types (say a List<Shape> with Rectangle, Circle and Triangle objects), I need to prevent objects of a certain type from being serialized (say Circle). What's the best way to achieve this? The JsonIgnore attribute seems to apply to object-properties and not entire types.

Upvotes: 1

Views: 303

Answers (1)

Ilija Dimov
Ilija Dimov

Reputation: 5299

There is no built in way to ignore objects of a certain type, that are part of a list of objects of polymorphic types, from being serialized. What you can do is write a custom JsonConverter and decorate the Circle class with it. Example:

public class CircleJsonConverter : JsonConverter
{

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        return;
    }

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

    public override bool CanConvert(Type objectType)
    {
        return true;
    }
}

and example of the Circle class:

[JsonConverter(typeof(CircleJsonConverter))]
public class Circle : Shape
{
    public uint R { get; set; }
}

You can implement the ReadJson method to be able to deserialize json string into instances of Circle class. Drawback of this solution is that you won't be able to serialize into json string using JSON.NET any instance of the Circle class.

Upvotes: 1

Related Questions