Unity コードで JSON を操作する組み込みの方法
JSON (JavaScript Object Notation) は広く使用されているデータ交換形式であり、これを Unity に統合すると、設定の処理、ゲームの進行状況の保存、または外部サービスとのデータ交換に強力になります。このガイドでは、Unity での JSON の操作の基礎を説明します。
ステップ 1: JSON を理解する
JSON は、キーと値のペアとネストされた構造で構成されます。
ステップ 2: Unity コードでの JSON の操作
Unity 'JsonUtility' クラスを通じて JSON のシリアル化と逆シリアル化を簡素化します。このガイドでは、外部ライブラリを使用せずに Unity で JSON を操作する基本的な手順を説明します。
- JSON 構造を作成します。
{
"playerName": "John Doe",
"playerLevel": 5,
"inventory": ["sword", "shield"]
}
- シリアル化 - C# オブジェクトから JSON への変換:
using UnityEngine;
[System.Serializable]
public class PlayerData
{
public string playerName;
public int playerLevel;
public string[] inventory;
}
public class SerializationExample : MonoBehaviour
{
void Start()
{
PlayerData playerData = new PlayerData
{
playerName = "John Doe",
playerLevel = 5,
inventory = new string[] { "sword", "shield" }
};
string json = JsonUtility.ToJson(playerData);
Debug.Log(json);
}
}
- 逆シリアル化 - JSON から C# オブジェクトへの変換:
using UnityEngine;
[System.Serializable]
public class PlayerData
{
public string playerName;
public int playerLevel;
public string[] inventory;
}
public class DeserializationExample : MonoBehaviour
{
void Start()
{
string jsonData = "{\"playerName\":\"John Doe\",\"playerLevel\":5,\"inventory\":[\"sword\",\"shield\"]}";
PlayerData playerData = JsonUtility.FromJson<PlayerData>(jsonData);
Debug.Log($"Name: {playerData.playerName}, Level: {playerData.playerLevel}");
Debug.Log("Inventory: " + string.Join(", ", playerData.inventory));
}
}
既知の制限事項
'JsonUtility' は、ラッピング クラスを使用しないオブジェクトの最上位配列 ('[{},{},{}]' など) のシリアル化と逆シリアル化を直接サポートしません。これを回避するには、ヘルパー クラスを使用して配列をラップします。以下に例を示します。
using UnityEngine;
[System.Serializable]
public class PlayerData
{
public string playerName;
public int playerLevel;
}
[System.Serializable]
public class PlayerDataArrayWrapper
{
public PlayerData[] players;
}
public class TopLevelArrayExample : MonoBehaviour
{
void Start()
{
// Serialization: Converting C# Object Array to JSON
PlayerData[] players = new PlayerData[]
{
new PlayerData { playerName = "John Doe", playerLevel = 5 },
new PlayerData { playerName = "Jane Smith", playerLevel = 8 }
};
PlayerDataArrayWrapper wrapper = new PlayerDataArrayWrapper { players = players };
string json = JsonUtility.ToJson(wrapper);
Debug.Log(json);
// Deserialization: Converting JSON to C# Object Array
string jsonData = "{\"players\":[{\"playerName\":\"John Doe\",\"playerLevel\":5},{\"playerName\":\"Jane Smith\",\"playerLevel\":8}]}";
PlayerDataArrayWrapper deserializedData = JsonUtility.FromJson<PlayerDataArrayWrapper>(jsonData);
foreach (var player in deserializedData.players)
{
Debug.Log($"Name: {player.playerName}, Level: {player.playerLevel}");
}
}
}
上記の例では、'PlayerDataArrayWrapper' クラスを使用して、シリアル化および逆シリアル化時に配列をラップします。'JsonUtility' のオブジェクトの最上位配列を処理する場合、このようなラッパー クラスを作成するのが一般的です。
結論
'JsonUtility' 外部ライブラリを使用せずに、JSON のシリアル化と逆シリアル化を直接簡素化します。Unity プロジェクトでの単純な JSON 操作には、このネイティブ アプローチを使用します。