Home > Mobile >  converting enums to json objects
converting enums to json objects

Time:05-13

I have two enums:

    enum myEnum
    {
        item_one = 1,
        item_two = 2,
    }

    enum myEnum2
    {
        item_four = 4,
        item_five = 5,
    } 

I would like to represent these as Json objects so that I can send then off when a http request is made. the goal is to have them look like:

{
  myEnum:{[
   {
     "code": 1, "definition": "item_one"
   },
   {
     "code": 2, "definition": "item_two"
   }
  ]},
  myEnum2:{[
   {
     "code": 4, "definition": "item_four"
   },
   {
     "code": 5, "definition": "item_five"
   }
  ]},
}

CodePudding user response:

I would create an in-between mapping object, that can be put through a serializer like Newtonsoft.Json or System.Text.Json:

// Out mapping object
class EnumMapper {
  public int Code { get; set; }
  public string Definition { get; set; }
}

// Create the target output format
var result = new Dictionary<string, List<EnumMapper>>();

// Go over an enum and add it to the dictionary
// Should properly be made into a method so it easier to add more enums
foreach(var enumValue in Enum.GetValue(typeof(myEnum))) {
  // List containing all values of a single enum
  var enumValues = new List<EnumMapper>();
  enumValues.Add(new EnumMapper {
    Code = (int)enumValue,
    Description = Enum.GetName(enumValue)
  });

  // Add the enum values to the output dictionary
  result.Add("myEnum", enumValues)
}

// Serialize to JSON
var json = JsonConvert.Serialize(result)

I haven't tested the above code - but you should be able to grasp the general idea from it.

  • Related