본문 바로가기

유니티

[Unity] Json Utility : 유니티에서 Json 읽기 쓰기

JsonData 클래스 만들기

[Serializable] 를 입력하여 직렬화를 시켜줍니다. (using System 을 해야함.)

GetType().Name으로 클래스이름을 가져올 수 있습니다.

[Serializable]
public class JsonData
{
    public string typeName;

    public JsonData()
    {
        typeName = GetType().Name;
    }
}

JsonData 클래스를 상속받아 저장할 클래스를 만듭니다.

생성자 옆에 base()를 붙여주어 부모클래스의 생성자가 실행되도록 합니다.

[Serializable]
public class PlayerData : JsonData
{
    public Vector3 pos;
    public int level;

    public PlayerData() : base()
    {
        
    }
}

Json 데이터 저장하기(쓰기)

JsonUtility.ToJson() 함수를 이용하여 데이터를 Json으로 바꿔줍니다.

file.Directory.Create()는 폴더가 없을 경우 폴더를 만들어줍니다.

private void SaveJsonData(JsonData data)
{
    string jsonData = JsonUtility.ToJson(data);
    string path = GetJsonSavePath(data.typeName);
    var file = new System.IO.FileInfo(path);
    file.Directory.Create();
    System.IO.File.WriteAllText(file.FullName, jsonData);
}

typeName을 파일이름으로 해서 경로를 지정해줍니다.

private string GetJsonSavePath(string typeName)
{
    return string.Format("Assets/JsonResource/{0}.json", typeName);
}

//Application.dataPath를 이용해서 리턴값을 수정해주면 똑같은곳에 저장됩니다.
//return Application.dataPath + string.Format("/JsonResource/{0}.json", typeName);

 

함수를 가져와서 데이터를 저장해줍니다.

private void SavePlayerData()
{
    var playeData = new PlayerData();
    playeData.pos = new Vector3(1, 2, 3);
    playeData.level = 2;

    SaveJsonData(playeData);
}

Json 데이터 불러오기(읽기)

default(T) 는 참조 형식일때 null을 반환합니다.

private T LoadJsonData<T>(string typeName)
{
    string path = GetJsonSavePath(typeName);
    var file = new System.IO.FileInfo(path);

    if (!file.Exists)
    {
        Debug.LogError("파일 없음: " + path);
        return default(T);
    }

    string jsonData = System.IO.File.ReadAllText(file.FullName);

    return JsonUtility.FromJson<T>(jsonData);
}

만들어준 함수를 사용해서 데이터를 불러옵니다.

private void LoadPlayerData()
{
    PlayerData playerData = new PlayerData();
    playerData = LoadJsonData<PlayerData>(playerData.typeName);

    if(playerData == null) 
    {
        return; 
    }

    Debug.Log("player pos: " + playerData.pos);
    Debug.Log("player level: " + playerData.level);
}