简体   繁体   中英

Cannot cast from source type to destination type Json

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);
     }
 }

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);

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM