首页 > 解决方案 > 在 Unity 3D 中使用从 WWW 接收的数据

问题描述

我有一个 API,每当我点击它时,我都会得到以下响应:

{
    "current_points": 2300,
    "tasks": [
        { "title": "Fire a player", "points": 200, "completed": true },
        { "title": "Buy a player", "points": 200, "completed": true },
        { "title": "Press conference", "points": 1000, "completed": false },
        { "title": "Set lineup", "points": 500, "completed": false },
        { "title": "Win a match", "points": 200, "completed": false }
    ]
}

现在我想分解这些数据并用它来更新我的“游戏结束”屏幕中的 UI。问题是我不知道如何分解它,以便我可以分别完成所有任务。

这是我第一次使用 API,因此将不胜感激。

标签: jsonrestunity3d

解决方案


您可以使用JsonUtility.FromJson创建您定义的类的实例以存储数据:

public class Task
{
    public string title ;
    public int points;
    public int completed ;
}

public class APIResponse
{
    public int current_points ;
    public Task[] tasks;
}

// In your main code

private void OnJsonResponseReceived(string jsonString)
{
    UpdateUI( JsonUtility.FromJson<APIResponse>(jsonString) ) ;
}

public void UpdateUI(APIResponse response)
{
    Debug.Log( response.current_points ) ;
    for( int i = 0 ; i < response.tasks.Length ; ++i )
    {
        Debug.LogFormat("Task '{0}' ({2} points) is {3}", response.tasks[i]., response.tasks[i]., response.tasks[i].completed ? "completed" : "not completed" ) ;
    }
}

推荐阅读