如何将字符串反序列化为枚举?

How can I deserialize string to enum?

我有一个国家列表,需要将 "DE" 转换为 CountryCode.DE。但是下面的代码不起作用。在这种情况下,有从字符串到枚举的简单方法吗?

    using System.Text.Json;
    using System.Text.Json.Serialization;
    class Program
    {
        [JsonConverter(typeof(JsonStringEnumConverter))]
        public enum CountryCodes
        {
            [Display(Name = "Japan", Description = "392")]
            JP,

            [Display(Name = "Germany", Description = "276")]
            DE,
        }

        static void Main()
        {
            var code = JsonSerializer.Deserialize<CountryCodes>("DE");
        }
    }

您可以使用 Enum 中的 TryParse 方法,如下所示:

bool isSuccess = Enum.TryParse("DE", out CountryCodes result);
if (!isSuccess) 
{ 
    //You can run any code you want in case of failure. 
}
else
{
    //You can use the variable result here which should contains the CountryCodes.DE value.
}