- Home /
MiniJson: Unable to Deserialize WWW response
I'm trying to deserialize a response to a WWW request like this:
IEnumerator requestScores(int level)
{
WWW jsonScores = new WWW(requestScoresURL + level);
yield return jsonScores; //Wait for download to complete
float elapsedTime = 0.0f;
while (!jsonScores.isDone)
{
elapsedTime += Time.deltaTime;
if (elapsedTime >= 10.0f) break;
yield return null;
}
if (!jsonScores.isDone || !string.IsNullOrEmpty(jsonScores.error))
{
Debug.LogError(string.Format("Fail Whale!\n{0}", jsonScores.error));
yield break;
}
string response = jsonScores.text;
Debug.Log(elapsedTime + " : " + response);
Dictionary<string, object> search = Json.Deserialize(response) as Dictionary<string, object>;
//(1) IDictionary dict = (IDictionary) Json.Deserialize(response);
foreach ( KeyValuePair <string, object> entry in search)
{
Debug.Log("key: " + entry.Key + ", value:" + entry.Value);
// do something with entry.Value or entry.Key
}
}
So I'm getting a proper "jsonScores.text" but Dictionary "search" comes out as null.
If I use IDictionary ( Comment //(1) ) I get: "InvalidCastException: Cannot cast from source type to destination type."
Answer by b0rtz · Oct 05, 2014 at 11:00 PM
Ok I found what was wrong in there, first I found out that Deserialize only worked with System.Object, then as I was getting multiple rows the object returned was an array of dictionaries instead of a single one.
This is the code that worked:
Dictionary<string, object>[] dictArray;
...
System.Object obj = JsonReader.Deserialize(json) as System.Object;
dictArray = (Dictionary<string, object>[]) obj;
foreach (Dictionary<string, object> row in dictArray)
{
// Do whatever with row
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer
Unity C# Deserialization dealing with extra properties 1 Answer
C#.How to Deserialize? 2 Answers