convert nested json to key value pairs c# code example
Example: print all the nested json key value pair c#
public static Dictionary<string, object> deserializeJson(this string json)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string, object> dictionary =
serializer.Deserialize<Dictionary<string, object>>(json);
return dictionary;
}
static void resolveEntry(Dictionary<string, object> dic, string SupKey)
{
// Each entry in the main dictionary is [Table-Key , Table-Value]
foreach (KeyValuePair<string, object> entry in dic)
{
if (entry.Value is Dictionary<string, object>) // for Meta and Data
resolveEntry((Dictionary<string, object>)entry.Value, entry.Key);
else
if (entry.Value is ICollection)
// Checks whether the current Table-Value in Table is Sub-Dictionary|Collection|Flat Object
{
foreach (var item in (ICollection)entry.Value)
// If the table base value is a collection of items then loop through them
{
if (item is Dictionary<string, object>)
// If the Collection-Item is a Dictionary then submit it for resolving
resolveEntry((Dictionary<string, object>)item, SupKey + " : " + entry.Key);
else
Console.WriteLine(item.ToString());
// If the Collection-Item is a Flat Object then output
}
}
else
Console.WriteLine(SupKey + " : " +
entry.Key.ToString() + "--->" + entry.Value.ToString());
// The Current Table-Value is Flat Object
}
}
// Caller :
Dictionary<string, object> dic = plsfobject.deserializeJson();
resolveEntry(dic, "Base");
Console.ReadKey();