[英]Deserialization of Json to NJsonSchema generated object with enums containing spaces
[英]JSON string to object using Enums
我有JSON字符串,類似於:
{"1":{"1":"driver","2":"New York, NY"},"2":{"3":"male","2":"Alabama"}}
我有兩個枚舉:
public enum StoragePrimaryKeys
{
Login = 1,
Account = 2
};
public enum StorageSecondaryKeys
{
JobTitle = 1,
JobId = 2,
JobLocation = 3,
RenewDate = 4,
ExpirationDate = 5
};
如何將該JSON反序列化為對象?
我想做下一件事:
var jss = new JavaScriptSerializer();
Dictionary<string, string> sData = jss.Deserialize<Dictionary<string, string>>(value);
string output = string.empty;
foreach (KeyValuePair<string, string> entry in sData)
{
if (Convert.ToInt32(entry.Key) == StorageSecondaryKeys.JobTitle) {
}
output += "\n key:" + entry.Key + ", value:" + entry.Value;
}
但是也許有更有效的方法?
我認為這是一個新問題,因為我在鍵中有數字,應該將其轉換為枚舉的字符串
謝謝。
看來您的數據模型應如下所示:
Dictionary<StoragePrimaryKeys, Dictionary<StorageSecondaryKeys, string>>
但是,通過實驗,我發現JavaScriptSerializer
不支持將枚舉用作字典鍵,因此您不能直接將其反序列化為此類對象。 因此,您可以反序列化為字符串鍵字典並使用Linq進行轉換:
var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, Dictionary<string, string>>>(value)
.ToDictionary(
p => (StoragePrimaryKeys)Enum.Parse(typeof(StoragePrimaryKeys), p.Key),
p => p.Value.ToDictionary(p2 => (StorageSecondaryKeys)Enum.Parse(typeof(StorageSecondaryKeys), p2.Key), p2 => p2.Value));
這將產生您想要的字典。
另外,您可以安裝json.net並直接將其反序列化為所需的字典,因為Json.NET確實支持枚舉鍵字典:
var dict = JsonConvert.DeserializeObject<Dictionary<StoragePrimaryKeys, Dictionary<StorageSecondaryKeys, string>>>(value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.