Unity

(Unity) JSON을 통한 데이터 처리 in Unity

Janny_ 2022. 10. 24. 20:28

JSON은 웹이나 네트워크에서 서버와 클라이언트 사이에서 데이터를 주고 받을 때 사용하는 개방형 표준 포멧입니다. JSON은 XML에 비해서 가독성이 좋고 직렬화(Serialize)와 비직렬화(Deserialize) 함수를 통해서 데이터에서 JSON 데이터로, JSON 데이터에서 데이터로 편하게 변환할 수 있다는 장점을 가지고 있습니다.

 

이러한 JSON 포맷은 유니티에서도 많이 사용되는데, 네트워크 게임을 개발할 때 게임에 필요한 데이터를 주고 받거나, 게임 진행 상황을 저장하거나, 게임 설정을 저장하는 방식으로도 사용할 수 있습니다.

 

유니티에서 기본 제공하는 JsonUtility는 컴팩트한 최소한의 기능을 제공하는데, 이를 통해 직렬화 / 역직렬화로 게임 내 데이터와 Json데이터의 상호 변환이 쉽게 가능합니다.

 

 

Json 데이터의 구조

{
    "id":"wergia",
    "level":10,
    "exp":33.3,
    "hp":400,
    "items":
    [
        "Sword",
        "Armor",
        "Hp Potion",
        "Hp Potion",
        "Hp Potion"
    ]
}

JSON의 데이터는 키(Key)와 값(Value) 쌍(Pair)로 이루어진 데이터를 저장하는데, items와 같이 배열로 된 데이터 역시 저장이 가능하고 객체 안에 객체를 넣는 것도 가능하며 위의 데이터 내용이 문자열로 이루어져 있기 때문에 사람이 알아보기가 매우 쉽습니다.

 

JSON 데이터에서 { } 는 객체를 의미하고, [ ] 는 순서가 있는 배열을 나타냅니다. 그리고 JSON은 정수, 실수, 문자열, 불리언, null 타입의 데이터 타입을 지원합니다.  JSON은 주석을 지원하지 않기 때문에, JSON 파일을 사람이 읽고 수정할 수 있도록 할 예정이라면, 키의 이름을 명확하게 정해서 이 값이 무엇을 의미하는 지 나타내는 것이 좋습니다.

 

JSON은 중간에 중괄호나 대괄호, 콜론, 쉼표 등이 하나라도 빠지는 작은 문법 오류에도 파일이 깨져버리고 파일을 읽어들일 수 없게 될 수 있기 때문에 조심해야 합니다.

 

 

 

JSON 데이터 처리 예시

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 
 
[System.Serializable] 
public class Data 
{ 
    public int m_nLevel; 
    public Vector3 m_vecPositon; 
 
    public void printData() 
    { 
        Debug.Log("Level : " + m_nLevel); 
        Debug.Log("Position : " + m_vecPositon); 
    } 
} 
 
public class JsonTest : MonoBehaviour 
{ 
    // Start is called before the first frame update 
    void Start() 
    { 
        Data data = new Data(); 
        data.m_nLevel = 12; 
        data.m_vecPositon = new Vector3(3.4f, 5.6f, 7.8f); 
 
        string str = JsonUtility.ToJson(data); 
        
        Debug.Log("ToJson : " + str); 
    } 
 
    // Update is called once per frame 
    void Update() 
    { 
         
    } 
}

클래스 오브젝트를 생성하고 데이터를 삽입한 뒤 Json형식으로 string에 넣습니다.

JsonUtility.ToJson(data)를 통해 Json 형식으로 변환하게 됩니다.

 

Json형식의 데이터를 다시 오브젝트 형으로 변환할 때는 다음과 같이 JsonUtility.FromJson 메서드를 사용하면 됩니다.

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 
 
[System.Serializable] 
public class Data 
{ 
    public int m_nLevel; 
    public Vector3 m_vecPositon; 
 
    public void printData() 
    { 
        Debug.Log("Level : " + m_nLevel); 
        Debug.Log("Position : " + m_vecPositon); 
    } 
} 
 
public class JsonTest : MonoBehaviour 
{ 
    // Start is called before the first frame update 
    void Start() 
    { 
        Data data = new Data(); 
        data.m_nLevel = 12; 
        data.m_vecPositon = new Vector3(3.4f, 5.6f, 7.8f); 
 
        string str = JsonUtility.ToJson(data); 
 
        Debug.Log("ToJson : " + str); 
 
        Data data2 = JsonUtility.FromJson<Data>(str);
        data2.printData(); 
    } 
 
    // Update is called once per frame 
    void Update() 
    { 
         
    } 
}

 

결과

실행 시 위와 같은 결과를 볼 수 있습니다.

 

 

 

 

Json 형태 파일로 저장 및 불러오기

using System.Collections; 
using System.Collections.Generic; 
using System.IO; 
using UnityEngine; 
 
[System.Serializable] 
public class Data 
{ 
    public int m_nLevel; 
    public Vector3 m_vecPositon; 
 
    public void printData() 
    { 
        Debug.Log("Level : " + m_nLevel); 
        Debug.Log("Position : " + m_vecPositon); 
    } 
} 
 
public class JsonTest : MonoBehaviour 
{ 
    // Start is called before the first frame update 
    void Start() 
    { 
        Data data = new Data(); 
        data.m_nLevel = 12; 
        data.m_vecPositon = new Vector3(3.4f, 5.6f, 7.8f); 
 
        string str = JsonUtility.ToJson(data); 
 
        Debug.Log("ToJson : " + str); 
 
       Data data2 = JsonUtility.FromJson<Data>(str);
        data2.printData(); 
 
        // file save 
 
        Data data3 = new Data(); 
        data3.m_nLevel = 99; 
        data3.m_vecPositon = new Vector3(8.1f, 9.2f, 7.2f); 
 
        File.WriteAllText(Application.dataPath + "/TestJson.json", JsonUtility.ToJson(data3)); 
 
        // file load 
 
        string str2 = File.ReadAllText(Application.dataPath + "/TestJson.json"); 
 
       Data data4 = JsonUtility.FromJson<Data>(str2);
        data4.printData(); 
    } 
 
    // Update is called once per frame 
    void Update() 
    { 
         
    } 
}

 

파일 저장

Application.dataPath는 현재 작업 폴더를 나타내며 이 경로에 File.WriteAlltext() 메서드를 통해 TestJson.json 파일이 생성됩니다.

 

파일 불러오기

File.ReadAllText() 메서드를 통해 경로의 TestJson.json 파일을 불러와 str2에 넣습니다.

그 뒤 JsonUtility.FromJson<Data>(str2)을 통해 json형식의 데이터를 변환하고 출력합니다.

 

결과

 

 

 

 

 

 

 

 

 

 

 

참고

https://scvtwo.tistory.com/18

https://wergia.tistory.com/164