json - 在 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,因此将不胜感激。
解决方案
您可以使用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" ) ;
}
}
推荐阅读
- node.js - Firebase onCall 方法在代码执行完成之前完成
- shopify - Shopify 仅在产品具有特定标签时才呈现一些 HTML
- javascript - 如何从 Express 中的请求中获取数据
- bash - 通过 GNU 并行将 args 传递给定义的 bash 函数
- svelte - 重定向 sveltekit 端点并将数据传递到页面
- c# - 从 .msg 文件路径创建 MailMessage 对象?
- python - python 正则表达式,其中一组选项在列表中最多可以出现一次,以任何顺序
- kotlin - 如何处理 Kotlin 中延迟列表以获取成功元素的异常?
- javascript - TypeError:message.client.commands.array 不是函数
- azure - 如何使用机器人作曲家将对话集属性存储在 azure 上?