我有兩個列舉:
enum myEnum
{
item_one = 1,
item_two = 2,
}
enum myEnum2
{
item_four = 4,
item_five = 5,
}
我想將這些表示為 Json 物件,以便在發出 http 請求時可以發送出去。目標是讓它們看起來像:
{
myEnum:{[
{
"code": 1, "definition": "item_one"
},
{
"code": 2, "definition": "item_two"
}
]},
myEnum2:{[
{
"code": 4, "definition": "item_four"
},
{
"code": 5, "definition": "item_five"
}
]},
}
uj5u.com熱心網友回復:
我會創建一個中間映射物件,它可以通過序列化程式,如Newtonsoft.Jsonor 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)
我還沒有測驗過上面的代碼——但你應該能夠從中掌握大致的想法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/472753.html
上一篇:從集合List<T>創建樹
