본문 바로가기
개발/Unity

유니티 - JsonUtility로 Json 파싱하기 : (1) 기본

by 피로물든딸기 2022. 5. 29.
반응형

Unity 전체 링크

 

JsonUtility로 Json 파싱하기

 

(1) Json Parsing
(2) Json Array Parsing (배열 파싱)
(3) Array of Objects in Json Array Parsing (배열 안에 있는 오브젝트 배열 파싱)
(4) Json Export (파일 출력, 내보내기)


*.json 파일을 파싱하여 출력해보자.

 

먼저 이번에 파싱할 파일(Lotto1.json)은 아래와 같다.

{
  "id":"1",
  "date":"2002-12-07",
  "number":[10,23,29,33,37,40],
  "bonus":16
}

 

대한민국에서 로또는 2002년 12월 07일(date)에 1회(id)를 시작하였고,

당첨 번호(number)는 10, 23, 29, 33, 37, 40이며, 보너스 번호(bonus)는 16이었다.

 

Lotto1.json 파일을 Resources/Json 폴더 아래에 두자.

 

이제 Ctrl + Shift + N으로 빈 오브젝트를 만든 후, ParsingJson.cs를 추가한다.

 

System.IO의 File.ReadAllText에서 path를 넣어주면 string으로 변환해준다.

using System.IO;

public class ParsingJson : MonoBehaviour
{
    void Start()
    {
        string filePath = "Assets/Resources/Json/Lotto1.json";
        string json = File.ReadAllText(filePath);
    }
}

 

하지만 대부분 빌드를 위해서 Resources 아래에 파일을 넣어두므로, Resources.Load를 이용해서 파일을 불러온다.

Resources.Load의 경우에는 Resources가 기본 경로이다. 

그리고 TextAsset을 이용해서 파일을 불러온다. 

TextAsset textAsset = Resources.Load<TextAsset>("Json/Lotto1");

이제 json을 class (또는 struct)로 만들어보자. 

JSON 포맷으로 변환하기 위해서는 [Serializable] 선언이 필요하므로 using System을 사용한다.

json의 프로퍼티대로 Lotto class를 정의하고 [Serializable]로 선언하였다.

그리고 값의 입력이 제대로 들어왔는지 출력하기 위해 printNumbers 메서드를 추가하였다.

using System; /* for Serializable */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ParsingJson : MonoBehaviour
{
    [Serializable]
    public class Lotto
    {
        public int id;
        public string date;
        public int[] number;
        public int bonus;

        public void printNumbers()
        {
            string str = "numbers : ";
            for (int i = 0; i < 6; i++) str += number[i] + " ";

            Debug.Log(str);
            Debug.Log("bonus : " + bonus);
        }
    }
    
    ...
}

 

JsonUtility의 FronJson을 이용하여 json을 class로 변환한다.

TextAsset의 text에서 읽은 값을 받는다.

 

    void Start()
    {
        TextAsset textAsset = Resources.Load<TextAsset>("Json/Lotto1");

        Debug.Log(textAsset.text);

        Lotto lt = JsonUtility.FromJson<Lotto>(textAsset.text);

        lt.printNumbers();
    }

 

textAsset.text에 파일을 제대로 읽어온 것을 알 수 있다.

그리고 Lotto class에 값이 제대로 들어오게 되었다.

 

하지만 만약 json에 없는 프로퍼티를 정의하면 어떻게 될까?

Lotto class에 불필요한 멤버 변수를 추가하고 printNumbers에서 확인해보자.

    [Serializable]
    public class Lotto
    {
        public int id;
        public string date;
        public int[] number;
        public int bonus;

        /* json에 없는 멤버 */
        public string teststring;
        public int testint;

        public void printNumbers()
        {
            string str = "numbers : ";
            for (int i = 0; i < 6; i++) str += number[i] + " ";

            Debug.Log(str);
            Debug.Log("bonus : " + bonus);

            Debug.Log("test : " + teststring + " " + testint);
        }
    }

 

아래와 같이 teststring에는 ""가 testint에는 0이 들어가게 된다.

 

즉, json에 알맞은 변수가 없더라고 에러를 발생하지는 않는다.

 

이제 bonus 번호를 수정하고 class를 json으로 변경해보자.

JsonUtility의 ToJson으로 간단히 해결할 수 있다.

string classToJson = JsonUtility.ToJson(lt);
Debug.Log(classToJson);

 

파일을 내보내고 싶다면 System.IO를 선언해서 File의 WriteAllText 메서드를 사용하면 된다.

File.WriteAllText(filePath, classToJson);

 

최종 코드는 아래와 같다.

using System; /* for Serializable */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ParsingJson : MonoBehaviour
{
    [Serializable]
    public class Lotto
    {
        public int id;
        public string date;
        public int[] number;
        public int bonus;

        /* json에 없는 멤버 */
        public string teststring;
        public int testint;

        public void printNumbers()
        {
            string str = "numbers : ";
            for (int i = 0; i < 6; i++) str += number[i] + " ";

            Debug.Log(str);
            Debug.Log("bonus : " + bonus);

            Debug.Log("test : " + teststring + " " + testint);
        }
    }

    void Start()
    {
        TextAsset textAsset = Resources.Load<TextAsset>("Json/Lotto1");

        Debug.Log(textAsset.text);

        Lotto lt = JsonUtility.FromJson<Lotto>(textAsset.text);

        lt.printNumbers();

        lt.bonus = 100;

        string classToJson = JsonUtility.ToJson(lt);
        Debug.Log(classToJson);
    }
}

(1) Json Parsing
(2) Json Array Parsing (배열 파싱)
(3) Array of Objects in Json Array Parsing (배열 안에 있는 오브젝트 배열 파싱)
(4) Json Export (파일 출력, 내보내기)

 

Unity Plus:

 

Easy 2D, 3D, VR, & AR software for cross-platform development of games and mobile apps. - Unity Store

Have a 2D, 3D, VR, or AR project that needs cross-platform functionality? We can help. Take a look at the easy-to-use Unity Plus real-time dev platform!

store.unity.com

 

Unity Pro:

 

Unity Pro

The complete solutions for professionals to create and operate.

unity.com

 

Unity 프리미엄 학습:

 

Unity Learn

Advance your Unity skills with live sessions and over 750 hours of on-demand learning content designed for creators at every skill level.

unity.com

반응형

댓글