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 작업을 수행하려면 이 기본 접근 방식을 사용하세요.

추천 기사
Unity에서 컷씬을 트리거하는 방법
Unity 코드에서 배열 및 목록 작업
Unity에서 비디오 파일을 재생하는 방법
Unity에서 값을 초기화하는 런타임 시작 시 메서드
Unity 코드에서 클래스 및 객체 생성
Unity에서 문자열 작업 및 텍스트 데이터 조작
Unity에서 더 나은 프로그래머가 되는 방법