0

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.

dbc
  • 104,963
  • 20
  • 228
  • 340
Alon Shmiel
  • 6,753
  • 23
  • 90
  • 138
  • Possible duplicate of [Deserializing JSON data to C# using JSON.NET](http://stackoverflow.com/questions/2546138/deserializing-json-data-to-c-sharp-using-json-net) – JEV Jan 04 '16 at 14:35
  • I think It's not cause I have numbers in the keys that should be translated to the strings of the enums – Alon Shmiel Jan 04 '16 at 14:42
  • try (http://stackoverflow.com/questions/2441290/json-serialization-of-enum-as-string) – Preet Singh Jan 04 '16 at 14:42

1 Answers1

1

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);
dbc
  • 104,963
  • 20
  • 228
  • 340