unity 移动端解析json
时间: 2023-06-11 11:10:29 浏览: 123
在 Unity 中解析 JSON 数据需要借助第三方库,比较常用的有 LitJSON 和 SimpleJSON。
下面是使用 LitJSON 解析 JSON 数据的示例代码:
```csharp
using UnityEngine;
using LitJson;
public class JsonParser : MonoBehaviour
{
public string jsonString; // JSON 字符串
void Start()
{
// 解析 JSON 字符串
JsonData jsonData = JsonMapper.ToObject(jsonString);
// 获取 JSON 数据中的某个字段的值
int score = (int)jsonData["score"];
string name = (string)jsonData["name"];
Debug.Log("Name: " + name + ", Score: " + score);
}
}
```
上述代码中,首先将 JSON 字符串转换成 JsonData 对象,然后通过索引器获取每个字段的值。
如果使用 SimpleJSON,代码类似:
```csharp
using UnityEngine;
using SimpleJSON;
public class JsonParser : MonoBehaviour
{
public string jsonString; // JSON 字符串
void Start()
{
// 解析 JSON 字符串
JSONNode jsonData = JSON.Parse(jsonString);
// 获取 JSON 数据中的某个字段的值
int score = jsonData["score"].AsInt;
string name = jsonData["name"].Value;
Debug.Log("Name: " + name + ", Score: " + score);
}
}
```
需要注意的是,使用 LitJSON 或 SimpleJSON 需要将对应的库文件导入到 Unity 项目中。在导入库文件后,可以在代码中使用对应的命名空间来访问库中的类型和方法。
阅读全文
相关推荐













