Blazor 封装JS组件使用 Json 转换器修正大小写以及名称冲突问题

类型化参数
我们已经看到我们可以将Options参数作为匿名对象传递给构造函数,但我们真的很想使用类型化对象来获得类型安全编程的优点。Options我们首先为仅定义placement字段的类型构造一个新类。

public class Options {     [JsonPropertyName(placement)]     public Placement Placement { get; set; } }  public enum Placement {     [Description(auto)] Auto,     [Description(auto-start)] AutoStart,     [Description(auto-end)] AutoEnd,     [Description(top)] Top,     [Description(top-start)] TopStart,     [Description(top-end)] TopEnd,     [Description(bottom)] Bottom,     [Description(bottom-start)] BottomStart,     [Description(bottom-end)] BottomEnd,     [Description(right)] Right,     [Description(right-start)] RightStart,     [Description(right-end)] RightEnd,     [Description(left)] Left,     [Description(left-start)] LeftStart,     [Description(left-end)] LeftEnd }  

我们为类和枚举添加了许多属性,定义了放置的所有可能选项。JsonPropertyName告诉库System.Text.Json属性Placement名称应该被序列化为placement. 我们添加了Description属性,因为这是最接近实现的地方,我们可以在其中定义不同名称的 JSON 对应项。我们必须定义这些不同的 JSON 对应项的原因是您不能在枚举的选项中使用破折号,例如top-start. 我们可以选择只使用字符串而不是枚举,但是使用枚举会限制出错的可能性。System.Text.Json不使用Description属性开箱即用,但我们可以定义一个自定义转换器,它可以在序列化为 JSON 时获取属性。在我们制作它时,让我们尝试将泛型考虑在内,以便它可以使用任何带有Description属性的枚举。我们在一个名为EnumDescriptionConverter.

class EnumDescriptionConverter<T> : JsonConverter<T> where T : IComparable, IFormattable, IConvertible {     public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)     {         throw new NotImplementedException();     }      public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)     {         FieldInfo fi = value.GetType().GetField(value.ToString());          var description = (DescriptionAttribute)fi.GetCustomAttribute(typeof(DescriptionAttribute), false);          writer.WriteStringValue(description.Description);     } } 

我们定义我们可以使用此类中的任何类型T,只要它实现了 IComparable、IFormattable 和 IConvertible。这几乎将其缩小为枚举。在整个课程中,这T被用作给定类型的占位符。我们还声明该类实现了JsonConverter我们传递 type的接口T。JsonConverter指定我们需要同时实现 aRead和Write方法。我们不会使用该Read方法,所以我们让它抛出一个异常。在该Write方法中,我们的目标是使用writer最后一行中所述的 编写字符串。为了获取可以添加到枚举的任何选项的所有属性,我们Reflection用来获取FieldInfo其中包含所有属性。然后我们从fia中检索DescriptionAttribute并将其转换为 a DescriptionAttribute。如果我们忘记为枚举中的一个选项添加属性,这可能会导致问题,Description但它现在应该可以工作。

然后我们必须告诉我们的类在序列化/反序列化字段Options时应该使用这个转换器。Placement

public class Options {     [JsonConverter(typeof(EnumDescriptionConverter<Placement>))]     [JsonPropertyName(placement)]     public Placement Placement { get; set; } }