简体   繁体   中英

Deserializing a model from an api that contains Enums

We're developing a web application using ASP.Net MVC 5 C#, I'm having difficulties coming up with a nice solution for my problem.

We're accessing an api that has a few enums coming across as text (ie "yes", "no", "notfound", "na") on the model itself I'd like to have strongly typed enums that store in the database as an integer (save a little space I think) the issue comes when we're deserializing the response from the api. In the response it will comes across as text (see above) where as the enums will be expecting an integer.

How is this done? I really hate asking questions where I haven't tried anything but my web searches hasn't resulted in anything. If you needed any code please let me know and I'll update the question with the segments needed. As of right now the model has several strongly typed enums and the api is returning strings of the enum values. by the way The enum texts are the same as the return values.

In-case it makes any difference we're also using EF Code First 6

You can use Enum.TryParse to convert the string to its enum value

public enum MyEnum
{
  NA
  Yes,
  No
}

then

MyEnum value = MyEnum.NA;
Enum.TryParse<MyEnum>(theTextValue, out value );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM