0

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"
   }
  ]},
}
1
  • Enums are aliases for integer values, not objects. What you ask isn't serialization, it's retrieving the enum value definitions and generating new objects from them. You can get an enum's values with Enum.GetValues and the names with Enum.GetNames or Enum.GetName Commented May 12, 2022 at 7:43

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Had to modify slightly to prevent duplicate keys in the results dictionary... moved result.add() out sife of the for loop as well as the declaration 'enumValues' list. Thank you, worked perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.