unity用json和服务器数据交互
阅读原文时间:2023年07月09日阅读:2

第一种类型:服务器json数据是个对象

///

/// 获取用户信息初始化信息 ///
void InitUserMessage()
{
//服务器ip端口和传入参数
string path = string.Format("{0}/GetUserInfo?UserId={1}", PublicJs.url_RequestPrefix, PublicJs.GUID);
StartCoroutine(GetUserInfo(path));
}
/// /// 从服务器获取数据 ///
/// 服务器ip和端口
///
IEnumerator GetUserInfo(string urlParh)
{
Debug.Log(urlParh);

    DownloadItem down = new DownloadItem(urlParh);  
    yield return down.www;

    string wwwText = down.Text();  
    Debug.Log(wwwText);  
    if (string.IsNullOrEmpty(wwwText) == false)  
    {  
        var curUser = Json.Deserialize(wwwText) as Dictionary<string, object>;  
        view.InitUserMessage(curUser\["UserName"\].ToString(), curUser\["ClassName"\].ToString(), curUser\["Coins"\].ToString());  
    }  
    else  
    {  
        Debug.Log("信息错误");  
    }  
}

第二种类型:服务器数据是对象数组

IEnumerator RefreshUIData()
{
string urlPath = string.Format("{0}/GetTrends?", PublicJs.url_RequestPrefix);
DownloadItem down = new DownloadItem(urlPath);
yield return down.www;
string wwwText = down.Text();
Debug.Log(urlPath);
Debug.Log(wwwText);
List listObject = Json.Deserialize(wwwText) as List;

    foreach (var i in listObject)  
    {  
        Dictionary<string, object> row = i as Dictionary<string, object>;  
        HYDTAts hydt = new HYDTAts();  
        hydt.ID = row\["ID"\].ToString();  
        hydt.Name = row\["Title"\].ToString();  
        hydtList.Add(hydt);  
    }

    //hydtList = CSVFileHelp.GetCsvHYDT();  
    //Debug.Log(hydtList.Count);

    int tp = 0;  
    ItemHYDT itemHYDT;  
    GameObject obj;  
    foreach (HYDTAts item in hydtList)  
    {  
        obj = NGUITools.AddChild(view.GridObj, view.ItemObj);  
        obj.name = tp.ToString("D3");  
        obj.AddComponent<UIDragScrollView>();  
        obj.transform.localPosition = new Vector3(0, -50 \* tp, 0);  
        itemHYDT = obj.AddComponent<ItemHYDT>();  
        itemHYDT.SetLabelText(item.Name);  
        itemHYDT.BindValue(item);  
        itemHYDT.OnClick += ItemHYDT\_OnClick;  
        tp++;  
    }

    yield return 0;  
}