Conversion from Enum to string

Asked

Viewed 485 times

2

Good afternoon!

I have the following situation, as return of a request I receive a json with various information. In c# convert this information to objects using Jsonconvert.Deserialize()..

Look at the return below:

{
"id": "AV654AS65D4AS654DASD65AS4DA6S5D4AS65D4",
"due_date": "2017-08-10",
"currency": "BRL",
"items_total_cents": 1800,
"status": "paid",
"updated_at": "2017-08-11T10:45:30-03:00",
"total_cents": 1800,
"total_paid_cents": 1620,
"paid_at": "2017-08-11T10:45:30-03:00",
"taxes_paid_cents": 128,
"paid_cents": 1620,
"payable_with": "bank_slip",
"paid": "R$ 16,20",
"transaction_number": 9999999999,
"payment_method": "bank_slip",
"created_at_iso": "2017-08-10T11:25:46-03:00",
"updated_at_iso": "2017-08-11T10:45:30-03:00",
"items": [
  {
    "id": "AV654AS65D4AS654DASD65AS4DA6S5D4AS65D4",
    "description": "PARCELA X Y Z",
    "price_cents": 1800,
    "quantity": 1,
    "created_at": "2017-08-10T11:25:46-03:00",
    "updated_at": "2017-08-10T11:25:46-03:00",
    "price": "R$ 18,00"
  }
],
"variables": [
  {
    "id": "1",
    "variable": "payment_data.bank",
    "value": "bradesco"
  },
  {
    "id": "2",
    "variable": "payment_data.occurrence_date",
  "value": "100817"
},
{
  "id": "3",
  "variable": "payment_data.transaction_identifier",
  "value": "110817027400"
},
{
  "id": "4",
  "variable": "payment_data.transaction_number",
  "value": "90801863"
},
{
  "id": "5",
  "variable": "payment_method",
  "value": "iugu_bank_slip"
}
]
}

In variables I have the following structure: id, variable and value. The variable field has predefined values, could convert these values to something similar to Enum? C# offers this gap?

guy:

EnumString{
 payment_data.bank,
 payment_data.occurrence_date, 
 payment_data.transaction_identifier,
 payment_data.transaction_number,
 payment_method
}
  • 1

    I’ve researched it several times and so far I haven’t found any way automatic to do this; you need to convert the value you have in the corresponding Enum. I usually assign a DefaultValue to the Enum and create conversion class/method to compare the values and return the Enum correspondent.

  • 1

    That? https://answall.com/q/123841/101 Or this? https://answall.com/q/82946/101

1 answer

2


i use the following function to enter a string and return the enum:

public static T GetEnum<T>(string s)
{
    Array arr = Enum.GetValues(typeof(T));
    foreach (var x in arr)
    {
        if (x.ToString().Contains(s))
            return (T)x;
    }
    return default(T);
}

in the code, I’m using the Contains, but you can make the comparison that’s best for you.

  • 1

    Thanks! I did the following: public string variable { set { variable = Getenum<Enumvars>(value.Replace('.','_')); } } public Enumvars variable; .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.