【问题标题】:JsonIgnore attribute not work in abstract classJsonIgnore 属性在抽象类中不起作用
【发布时间】:2021-04-23 10:53:20
【问题描述】:

我不想在json文件中保存一些属性,所以我使用了 [JsonIgnore] 属性但是不起作用并且所有属性都被保存了

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

我也使用下面的转换器来解决多态问题

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

这是我的演示

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

我希望 FileNameboo 不会保存在文件中,但它们都保存了

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

【问题讨论】:

    标签: c# json .net-core system.text.json


    【解决方案1】:

    您的Write 方法提取所有属性而不对JsonIngoreAttribute 进行任何处理。

    因为 GetType().GetProperties() 对此属性一无所知,它会返回您拥有的所有属性。

    如果你想忽略这个属性的属性,你需要像这样修改你的代码。

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

    【讨论】:

      猜你喜欢
      • 2011-02-26
      • 1970-01-01
      • 2017-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多