//Here is the Json
{
"groups": null,
"data": [{
"type": 123,
"name": "Name123"
},
{
"type": 567,
"name": "SecondName"
}
],
"total": 2
}
// I am then deserializing my json to either dictionary or list.. in this case it would be a List.. and then I am using a foreach loop to first get the Type..
result[t].GetType() gives me the exception
var result = Helpers.JsonHelper.DeserializeToDictionaryOrList(jsonString);
foreach (var t in result.Keys)
{
var actualType = result[t].GetType();
}
//Here the DeserializeToDictionaryOrList method for reference
public static class JsonHelper
{
public static dynamic DeserializeToDictionaryOrList(string jsonString, bool isArray = false)
{
if (!isArray)
isArray = jsonString.Substring(0, 1) == "[";
if (!isArray)
{
var responseJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
var copyOfResponseJson = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> myDictionary in responseJson)
{
if (myDictionary.Value is JObject)
copyOfResponseJson.Add(myDictionary.Key, DeserializeToDictionaryOrList(myDictionary.Value.ToString()));
else if (myDictionary.Value is JArray)
copyOfResponseJson.Add(myDictionary.Key, DeserializeToDictionaryOrList(myDictionary.Value.ToString(), true));
else
copyOfResponseJson.Add(myDictionary.Key, myDictionary.Value);
}
return copyOfResponseJson;
}
else
{
var responseJson = JsonConvert.DeserializeObject<List<object>>(jsonString);
var copyOfResponseJson = new List<object>();
foreach (var myDictionary in responseJson)
{
if (myDictionary is JObject)
copyOfResponseJson.Add(DeserializeToDictionaryOrList(myDictionary.ToString()));
else if (myDictionary is JArray)
copyOfResponseJson.Add(DeserializeToDictionaryOrList(myDictionary.ToString(), true));
else
copyOfResponseJson.Add(myDictionary);
}
return copyOfResponseJson;
}
}
What I have tried:
I am not sure why this is causing the exception.. it was just fine with another Json.. I am guessing because first time result[t] is groups and the value in the json is null.. I am not really sure about this..