본문 바로가기
개발/Unity

유니티 - JsonUtility로 Json 파싱하기 : (3) 오브젝트 배열 파싱

by 피로물든딸기 2022. 6. 25.
반응형

Unity 전체 링크

 

JsonUtility로 Json 파싱하기

 

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


이전 글에서 사용한 json 배열 중 오브젝트 1개는 아래와 같다.

    {
      "id": "0",
      "date": "   0-00-00",
      "number": [0,0,0,0,0,0],
      "bonus": 0
    }

 

이 오브젝트에 다시 오브젝트 배열이 있는 경우를 생각해보자.

test 내부에 { int, string, int[] } 오브젝트가 배열로 있다.

    {
      "id": "0",
      "date": "   0-00-00",
      "number": [0,0,0,0,0,0],
      "bonus": 0,
      "test": [
          {
              "test1": 1,
              "test2": "1",
              "test3": [ 1, 2, 3 ]
          },
          {
              "test1": 2,
              "test2": "2",
              "test3": [ 2, 3, 4, 5 ]
          },
          {
              "test1": 3,
              "test2": "3",
              "test3": [ 3, 4, 5, 6, 7 ]
          },
          {
              "test1": 4,
              "test2": "4",
              "test3": [ 4, 5, 6, 7, 8, 9 ]
          }
      ]
    }

 

즉, 아래의 json을 파싱해보자.

{
  "winning":[
    {
      "id": "0",
      "date": "   0-00-00",
      "number": [0,0,0,0,0,0],
      "bonus": 0,
      "test": [
          {
              "test1": 1,
              "test2": "1",
              "test3": [ 1, 2, 3 ]
          },
          {
              "test1": 2,
              "test2": "2",
              "test3": [ 2, 3, 4, 5 ]
          },
          {
              "test1": 3,
              "test2": "3",
              "test3": [ 3, 4, 5, 6, 7 ]
          },
          {
              "test1": 4,
              "test2": "4",
              "test3": [ 4, 5, 6, 7, 8, 9 ]
          }
      ]
    },
    {
      "id": "1",
      "date": "2002-12-07",
      "number": [10,23,29,33,37,40],
      "bonus": 16,
      "test": [
          {
              "test1": 1,
              "test2": "1",
              "test3": [ 1, 2, 3, 4 ]
          },
          {
              "test1": 2,
              "test2": "2",
              "test3": [ 2, 3, 4, 5, 6, 7 ]
          }
      ]
    },
    {
      "id": "2",
      "date": "2002-12-14",
      "number": [9,13,21,25,32,42],
      "bonus": 2,
      "test": [
          {
              "test1": 1,
              "test2": "1",
              "test3": [ 1, 2, 3, 4, 5, 6 ]
          }
      ]
    }
  ]
}

먼저 새로운 class를 정의한다.

추가된 오브젝트와 같은 타입을 가지도록 정의하고 Serializable로 선언해야 한다.

    [Serializable]
    public class testCase //aray of objects
    {
        public int test1;
        public string test2;
        public int[] test3;
    }

 

그리고 기존이 Lotto 클래스에 testCast를 배열로 추가한다.

디버깅을 위해 printNumbers도 변경하였다.

    [Serializable]
    public class Lotto
    {
        public int id;
        public string date;
        public int[] number;
        public int bonus;
        public testCase[] test; /* 추가 */

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

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

            for (int i = 0; i < test.Length; i++)
            {
                Debug.Log("test1: " + test[i].test1);
                Debug.Log("test2: " + test[i].test2);

                for (int k = 0; k < test[i].test3.Length; k++)
                    Debug.Log("test3 [" + k + "] " + test[i].test3[k]);
            }
        }
    }
    
    public class LottoNumbers
    {
        public Lotto[] winning;
    }

 

이제 Start에서 classToJson을 확인하거나 콘솔창을 확인하면 된다.

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

        LottoNumbers lottoList = JsonUtility.FromJson<LottoNumbers>(textAsset.text);

        foreach (Lotto lt in lottoList.winning)
        {
            lt.printNumbers();
            Debug.Log("=============");
        }

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

 

최종 코드는 다음과 같다.

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

public class ParsingJson : MonoBehaviour
{
    [Serializable]
    public class testCase //aray of objects
    {
        public int test1;
        public string test2;
        public int[] test3;
    }

    [Serializable]
    public class Lotto
    {
        public int id;
        public string date;
        public int[] number;
        public int bonus;
        public testCase[] test; /* 추가 */

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

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

            for (int i = 0; i < test.Length; i++)
            {
                Debug.Log("test1: " + test[i].test1);
                Debug.Log("test2: " + test[i].test2);

                for (int k = 0; k < test[i].test3.Length; k++)
                    Debug.Log("test3 [" + k + "] " + test[i].test3[k]);
            }
        }
    }

    public class LottoNumbers
    {
        public Lotto[] winning;
    }

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

        LottoNumbers lottoList = JsonUtility.FromJson<LottoNumbers>(textAsset.text);

        foreach (Lotto lt in lottoList.winning)
        {
            lt.printNumbers();
            Debug.Log("=============");
        }

        string classToJson = JsonUtility.ToJson(lottoList);
        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

 

반응형

댓글