0

I'm retrieving a json file from my server and then using Json to deserialize the content. How ever I keep receiving this error:

Cannot cast from source type to destination type

I was following the steps of the Minijson script but yet this error still comes up. Some help would be appreciated.

 void Start () {


     //creating url
     image1Request = new WWW("http://development.someurl.com/MoreGames/MoreGames.json");
     StartCoroutine(ImageOne(image1Request));
 }

 IEnumerator ImageOne(WWW www)
 {
     //wait until url is loaded
     yield return www;
     //load image into texture slot
     if (www.error == null)
     {
         //assigning URLS
         var dict = Json.Deserialize(www.text) as Dictionary<string,object>;
         Debug.Log(www.text);
         Debug.Log("deserialized: " + dict.GetType());
         Debug.Log("dict['string']: " + (string)dict["widget"]);

     }

     else
     {
         Debug.Log("WWW Error: " + www.error);
     }
 }
d4Rk
  • 6,622
  • 5
  • 46
  • 60
bru345
  • 1
  • 2

2 Answers2

0

Instead of using

var dict = Json.Deserialize(www.text) as Dictionary<string,object>;

I would suggest you to use the following code snippet

var dict = new System.Web.Script.Serialization.JavaScriptSerializer(); Dictionary<string, object> dictObject =(Dictionary<string,object>)jsSerializer.DeserializeObject(www.text);
mr. Holiday
  • 1,780
  • 2
  • 19
  • 37
0

Your Dictionary's value type is object. You are trying to cast an object type to string. It should be corrected to :

(object)dict["widget"]

I'm not sure what you are trying to log there, but if it is the widget object's name it should go like this :

Debug.Log("dict['string']: " + ((object)dict["widget"]).ToString());
Nimesh
  • 168
  • 5
  • Problem is I get the object but not the string that it contains. – bru345 Jul 21 '15 at 10:05
  • @bru345 What is the type of your object? If your object is a custom type, you'll have to cast it to that type and access the information. Something like `YourType type = (YourType)dic["widget"]; Debug.log(type.YourString);` – Nimesh Jul 21 '15 at 10:11
  • Sorry I don't understand your question. My Json contains an array which I'm trying to read and save into a dictionary as a string. – bru345 Jul 21 '15 at 10:21
  • I'm confused about what you are trying to achieve. See if this answers your question. (http://stackoverflow.com/questions/20727787/deserialize-json-string-to-dictionarystring-object) – Nimesh Jul 21 '15 at 11:02
  • Thank you for the link but I'm not having issue with the dictionary returning null. The main root of my problem/understanding is that I cannot read the strings that I have stored in the dictionary. That's ultimately the problem. – bru345 Jul 21 '15 at 11:32