c# - 是否有 System.Text.Json 属性只允许有效的枚举值?
问题描述
我有一个枚举:
public enum TaxType : byte
{
None = 0,
GSTCanada = 5,
HSTOntario = 13,
HSTOther = 15
}
它在 json 中由一个数字给出。例如:
{"TaxType": 13, ...}
public class OrderInfo
{
public TaxType TaxType { get; set; }
/// ...
}
它将成功反序列化,但如果值为NOT (0 OR 5 OR 13 OR 15)
.
这可以通过使用属性来实现System.Text.Json
吗?
解决方案
您可以为您的枚举创建一个自定义转换器,如下所示:
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
var jsonOpt = new JsonSerializerOptions();
jsonOpt.Converters.Add(new CustomEnumConverter());
Console.WriteLine(JsonSerializer.Deserialize<OrderInfo>("{\"TaxType\":14}", jsonOpt).TaxType);
public enum TaxType
{
None = 0,
GSTCanada = 5,
HSTOntario = 13,
HSTOther = 15
}
public class OrderInfo
{
public TaxType TaxType { get; set; }
}
public class CustomEnumConverter : JsonConverter<TaxType>
{
public override TaxType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var value = reader.GetInt32();
if (Enum.IsDefined(typeToConvert, value))
{
return (TaxType) value;
}
throw new Exception("Value is invalid");
}
public override void Write(Utf8JsonWriter writer, TaxType value, JsonSerializerOptions options)
{
writer.WriteNumber("taxType", (decimal)(int)value);
}
}
显然这不是完全通用的,你需要做一些工作,但你明白了。
推荐阅读
- r - 根据R中的分层条件添加带有字母的列
- java - 无法定位元素:通过 POM 执行代码时出错,通过单个 main() 程序执行时相同的定位器工作正常
- 3d - 3d 形状填充连接到 P5.js webGL 上的第一个顶点
- angular - 使用 Angular 7 http 拦截器加载微调器在页面重新加载时不起作用
- ag-grid - AG-GRID 值格式化程序不适用于动态生成的货币
- reactjs - 实现 onSnapshot 函数以获取 reactjs 代码中的实时更新
- javascript - 使用 const 关键字 Javascript 声明数组
- python - OSError:SavedModel 文件不存在于:../dnn/mpg_model.h5/{saved_model.pbtxt|saved_model.pb}
- php - Algolia:使用 CURL (PHP) 获取数据返回的结果与使用 places.js 的示例结果不同
- dart - 在 Dart 中创建一组独特的地图