2014-01-18 43 views
0

首先,我必须指出,我对C#非常陌生。 我正在开发一个使用Unity3D的应用程序,部分应用程序要求我解析存储在我的服务器上的JSON文件。C#Unity3D JSON挂起

我遇到的问题是,有时一切正常,而其他时候应用程序挂在下载JSON。我没有收到任何错误,脚本从未达到100%的进展。

这里是我的代码:

public IEnumerator DownloadJSONFile(string url) 
{ 
     Debug.Log("JSON URL: "+ url); 
     mJsonInfo = new WWW(url); 
     yield return mJsonInfo; 

     mIsJSONRequested = true; 
} 
private void LoadJSONData(string jsonUrl) 
{ 

    Debug.LogWarning("LoadJSONData, url= "+jsonUrl); 

    if(!mIsJSONRequested){ 

     StartCoroutine(DownloadJSONFile(jsonUrl)); 

    } else { 

     if(mJsonInfo.progress >= 1) 
     { 


      if(mJsonInfo.error == null) 
      { 

       //** PARSE THE JSON HERE **// 

      }else 
      { 
       Debug.LogError("Error downloading JSON"); 
       mIsLoadingData = false; 
      } 


     } else { 
      Debug.LogWarning("!! ### JSON DOWNLOADING: "+mJsonInfo.progress+"%"); 
      if(mJsonInfo.error != null) 
       { 
        Debug.LogError("Error downloading JSON"); 
        Debug.LogError("JSON Error:"+mJsonInfo.error); 
        mIsLoadingData = false; 
       } 
     } 
    } 
} 

就像我说的,的JSON数据被几乎立即加载时间的50%,而50%的时间进度从未达到1.我从来没有收到一个错误形式为mJsonInfo.error变量。

任何有关我在做什么错误的建议将不胜感激!

回答

0

你需要等到下载完成。

正如documentation说你需要:

var www = new WWW(...); 
yield return www; 

所以,你需要从void修改方法的返回类型为IEnumerator

private IEnumerator LoadJSONData(string jsonUrl) 
{ 
    Debug.LogWarning("LoadJSONData, url= "+jsonUrl); 

    if(!mIsJSONRequested) 
    { 
     // Gets the json book info from the url 
     mJsonInfo = new WWW(jsonUrl); 
     yield return mJsonInfo; //Wait for download to complete 
     mIsJSONRequested = true; 
    } 
    else 
    { 
     ... 
    } 
} 
+0

感谢您的建议阿尔贝托,我已经尝试过(用已更新的代码编辑我的问题),但我仍然遇到同样的问题。有时它起作用,有时它不起作用 –

0

isDone是你需要的,

WWW lWWW = new WWW(...) 
if(lWWW.isDone) 
then parse it 
0

我发现这个问题,我想我会后我的解决方案,任何人都遇到同样的问题。 最后的解决方案是服务器上的JSON文件。我使用PHP(CakePHP)生成JSON,当通过浏览器打开PHP生成的文件时,响应时间是即时的,但是从我的移动应用程序出于某种原因它会挂起。所以我改变了我的服务器端代码来实际创建和更新一个实际的JSON文件,现在一切正常。