使用Enums的JSON字符串到对象

时间:2016-01-04 14:30:07

标签: c# json deserialization javascriptserializer

我有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;
}

但也许有更有效的方式?

我认为这是一个新问题,因为我的密钥中的数字应该转换为枚举字符串

感谢。

1 个答案:

答案 0 :(得分:1)

您的数据模型似乎应如下所示:

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确实支持枚举词典:

    var dict = JsonConvert.DeserializeObject<Dictionary<StoragePrimaryKeys, Dictionary<StorageSecondaryKeys, string>>>(value);