milad ghasemi
milad ghasemi

Reputation: 69

JsonIgnore attribute not work in abstract class

I do not want some properties to be saved in the json file, so I used [JsonIgnore] Attribute but Does not work and all properties are saved

public abstract class SettingBase
{
    [JsonIgnore]
    public abstract string FileName { get; set; }

    public void Save()
    {
        JsonFile.Save(FileName, this);
    }
}

public static class JsonFile
{
    public static void Save<T>(string fileName, T @object)
    {
        using (StreamWriter writer = File.CreateText(fileName))
        {
            options = new JsonSerializerOptions();
            options.Converters.Add(new PolymorphicJsonConverter<T>());
            string json = JsonSerializer.Serialize(@object, options);
            writer.Write(json);
        }
    }
}

I also use the following converter to solve the polymorphic problem

public class PolymorphicJsonConverter<T> : JsonConverter<T>
{
    public override bool CanConvert(Type typeToConvert)
    {
        return typeof(T).IsAssignableFrom(typeToConvert);
    }

    public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }

    public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
    {
        if (value is null)
        {
            writer.WriteNullValue();
            return;
        }

        writer.WriteStartObject();
        foreach (var property in value.GetType().GetProperties())
        {
            if (!property.CanRead)
                continue;
            var propertyValue = property.GetValue(value);
            writer.WritePropertyName(property.Name);
            JsonSerializer.Serialize(writer, propertyValue, options);
        }
        writer.WriteEndObject();
    }
}

and this is my demo

public class DemoSettings : SettingBase
{
    [JsonIgnore]
    public bool boo { get; set; }
    public int integ { get; set; }
    public string str { get; set; }

    public override string FileName { get; set; } = "test.json";
}

I expect FileName and boo not to be saved in the file, but they are all saved

{
  "boo": true,
  "integ": 25,
  "str": "sss",
  "FileName": "test.json"
}

Upvotes: 1

Views: 674

Answers (1)

Dmitriy Korolev
Dmitriy Korolev

Reputation: 288

You Write method extract all properties without any processing of JsonIngoreAttribute.

Because GetType().GetProperties() knows nothing about this attribute it returns all properties that you have.

If you want to ignore properties with this attribute, you need to modify your code something like this.

if (!property.CanRead || property.GetCustomAttribute<JsonIgnoreAttribute>() != null)
    continue;

Upvotes: 1

Related Questions