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.

3

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.