I have a simple key/value list in JSON being sent back to ASP.NET via POST. Example:
{ \"key1\": \"value1\", \"key2\": \"value2\"}
I've added upon the code submitted by jSnake04 and Dasun herein. I've added code to create lists of objects from JArray
instances. It has two-way recursion but as it is functioning on a fixed, finite tree model, there is no risk of stack overflow unless the data is massive.
///
/// Deserialize the given JSON string data ( ) into a
/// dictionary.
///
/// JSON string.
/// Deserialized dictionary.
private IDictionary DeserializeData(string data)
{
var values = JsonConvert.DeserializeObject>(data);
return DeserializeData(values);
}
///
/// Deserialize the given JSON object ( ) into a dictionary.
///
/// JSON object.
/// Deserialized dictionary.
private IDictionary DeserializeData(JObject data)
{
var dict = data.ToObject>();
return DeserializeData(dict);
}
///
/// Deserialize any elements of the given data dictionary ( )
/// that are JSON object or JSON arrays into dictionaries or lists respectively.
///
/// Data dictionary.
/// Deserialized dictionary.
private IDictionary DeserializeData(IDictionary data)
{
foreach (var key in data.Keys.ToArray())
{
var value = data[key];
if (value is JObject)
data[key] = DeserializeData(value as JObject);
if (value is JArray)
data[key] = DeserializeData(value as JArray);
}
return data;
}
///
/// Deserialize the given JSON array ( ) into a list.
///
/// Data dictionary.
/// Deserialized list.
private IList