-2

I have a list of countries, and need to convert "DE" to CountryCode.DE. But the following code does not work. Is there a simple way to go from string to enum in this case?

    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");
        }
    }
dbc
  • 91,441
  • 18
  • 186
  • 284
fk69
  • 29
  • 3
  • _"the following code does not work."_ - Can you explain what does not work? What result do you get? And what are you expecting? – phuzi Mar 04 '22 at 13:11
  • 4
    A single string isn't really JSON; that might work if you had a class that *had* a `CountryCodes` property, and you deserialized `{"Country":"DE"}` – Marc Gravell Mar 04 '22 at 13:16
  • 1
    Try [`Enum.Parse`](https://docs.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-6.0) or the `TryParse` variant. – phuzi Mar 04 '22 at 13:23
  • Your problem is that your JSON is malformed. A JSON string literal needs to be quoted **inside the JSON itself** so you need to do `JsonSerializer.Deserialize("\"DE\"");`. See https://dotnetfiddle.net/RnOLTz. See [Deserialize a single DateTime object with JsonConvert](https://stackoverflow.com/a/50522936/3744182) for a similar question. – dbc Mar 04 '22 at 14:21
  • Though I don't see why you are using a JSON serializer to parse an enum name when you can just use `Enum.Parse()`; as written your question is a duplicate of [Convert a string to an enum in C#](https://stackoverflow.com/q/16100/3744182). But in your question you mention having a *list of countries* so maybe the actual string you need to parse is more complicated? If so, please [edit] your question to provide a [mcve]. – dbc Mar 04 '22 at 14:27

1 Answers1

3

You can use the TryParse method from Enum, like this:

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.
}
Paul Karam
  • 3,771
  • 6
  • 30
  • 47
  • 1
    Just one thing: If you are going to throw in case of failed parse anyway, you could have used as well `Enum.Parse` ... – Fildor Mar 04 '22 at 13:21