I have the method to Deserialize my json to Dictionary<string,object> but I am having trouble when my json is an object to turn that into Dictionary<string,object>.
I am getting an error on my second foreach loop
Error: cannot implicitly convert type 'system.collections.generic.dictionary<string, object=""> to 'system.collections.generic.keyvaluepair<string, object="">
//Here is the method
public static Dictionary<string, object> DeserializeToDictionary(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, DeserializeToDictionary(myDictionary.Value.ToString()));
else if (myDictionary.Value is JArray)
copyOfResponseJson.Add(myDictionary.Key, DeserializeToDictionary(myDictionary.Value.ToString(), true));
else
copyOfResponseJson.Add(myDictionary.Key, myDictionary.Value);
}
return copyOfResponseJson;
}
else
{
var resposneJson1 = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(jsonString);
var copyOfResponseJson2 = new Dictionary<string, object>();
foreach(KeyValuePair<string, object> myDictionary in resposneJson1)
{
if (myDictionary.Value is JObject)
copyOfResponseJson2.Add(myDictionary.Key, DeserializeToDictionary(myDictionary.Value.ToString()));
else if (myDictionary.Value is JArray)
copyOfResponseJson2.Add(myDictionary.Key, DeserializeToDictionary(myDictionary.Value.ToString(), true));
else
copyOfResponseJson2.Add(myDictionary.Key, myDictionary.Value);
}
return copyOfResponseJson2;
}
//Updating the Question with one of the Json I am trying the Deserialize
{
"groups": null,
"data": [{
"type": 123,
"name": "Name123"
},
{
"type": 567,
"name": "SecondName"
}
],
"total": 2
}
What I have tried:
I am not sure how to fix this error... Any help would be really great.