unity 解析json
时间: 2023-09-03 16:11:11 浏览: 65
解析 JSON 在 Unity 中可以通过 JsonUtility 类来实现。JsonUtility 类是 Unity 提供的一种快速解析和序列化 JSON 数据的方式,它可以将 JSON 数据转换为 C# 对象,并且也可以将 C# 对象序列化为 JSON 数据。
以下是一个简单的示例代码,演示了如何使用 JsonUtility 类来解析 JSON 数据:
```csharp
using UnityEngine;
using System.Collections;
[System.Serializable]
public class PlayerData {
public string playerName;
public int playerLevel;
}
public class JsonExample : MonoBehaviour {
void Start () {
string json = "{ \"playerName\": \"Tom\", \"playerLevel\": 5 }";
PlayerData playerData = JsonUtility.FromJson<PlayerData>(json);
Debug.Log("Player Name: " + playerData.playerName);
Debug.Log("Player Level: " + playerData.playerLevel);
}
}
```
在此示例中,我们首先定义了一个名为 PlayerData 的 C# 类,它包含两个公共字段:playerName 和 playerLevel。然后我们创建了一个 JsonExample 类,并在 Start() 方法中定义了一个 JSON 字符串,并使用 FromJson() 方法将其解析为 PlayerData 对象。最后,我们使用 Debug.Log() 方法输出了解析得到的对象的两个字段的值。
需要注意的是,JsonUtility 类只能解析公共字段(public field)或属性(public property),而不能解析私有字段或属性。因此,为了让 JsonUtility 类可以正确解析 JSON 数据,我们需要将要解析的类的字段或属性都定义为公共的。
希望这个简单的示例能够帮助你快速了解如何在 Unity 中解析 JSON 数据。