我有一个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,因此将不胜感激。
答案 0 :(得分:3)
您可以使用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" ) ;
}
}