在Unity中,序列化和反序列化可以通過對(duì)對(duì)象進(jìn)行標(biāo)記和使用JsonUtility類來(lái)實(shí)現(xiàn)。
[System.Serializable]
public class PlayerData
{
public string playerName;
public int playerLevel;
}
然后,可以使用JsonUtility.ToJson方法將對(duì)象序列化為JSON格式的字符串:
PlayerData player = new PlayerData();
player.playerName = "Alice";
player.playerLevel = 10;
string jsonData = JsonUtility.ToJson(player);
string jsonData = "{\"playerName\":\"Bob\",\"playerLevel\":15}";
PlayerData player = JsonUtility.FromJson<PlayerData>(jsonData);
Debug.Log("Player Name: " + player.playerName);
Debug.Log("Player Level: " + player.playerLevel);
這樣就可以實(shí)現(xiàn)對(duì)象的序列化和反序列化操作。需要注意的是,JsonUtility類只支持Unity內(nèi)置類型的序列化,對(duì)于自定義類型,需要手動(dòng)實(shí)現(xiàn)序列化和反序列化方法。