简体   繁体   中英

JSON string to object using Enums

I have JSON string, something like:

{"1":{"1":"driver","2":"New York, NY"},"2":{"3":"male","2":"Alabama"}}

I have two enums:

public enum StoragePrimaryKeys
{
    Login = 1,
    Account = 2
};

public enum StorageSecondaryKeys
{
    JobTitle = 1,
    JobId = 2,
    JobLocation = 3,
    RenewDate = 4,
    ExpirationDate = 5
};

How can I deserialize this JSON to an object?

I thought to do the next thing:

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

But maybe there is more efficient way?

I think It's a new question cause I have numbers in the keys that should be translated to the strings of the enums

Thanks.

It appears your data model should be as follows:

Dictionary<StoragePrimaryKeys, Dictionary<StorageSecondaryKeys, string>>

However, from experimentation, I found that JavaScriptSerializer does not support enums as dictionary keys, so you cannot deserialize to such an object directly. Thus you could deserialize to string-keyed dictionaries and convert using 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));

This will produce the dictionary you want.

Alternatively, you could install and deserialize directly to the desired dictionary, since Json.NET does support enum-keyed dictionaries:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM