본문 바로가기
유니티

JSON (JavaScript Object Notation)

by SUGI_ 2023. 8. 23.

통신을 위한 (데이터 주고 받기) 

 

저장할 내용 

ID 홍길동

비밀번호 1234

나이 23

 

-> Json 형태로 변경 (문자열 string)

딕셔너리 -> Key Value

Key : 무조건 문자열

Value : 문자열, int, float, bool, 배열, 또 다른 JSON

 

JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language Standard ECMA-262 3rd Edition

www.json.org

{
	"ID :"홍길동",
	"PS" : "1234",
	"AGE" : 23
}

 

+ 또 다른 형태 XML - 데이터를 만드는 형식이 존재한다! (그냥 알고 있기)

 

구조체와 클래스의 차이

구조체 struct 값타입 / 클래스 class 참조타입

 

구조체를 사용하는 이유는 클래스 사용시에 참조로인한 시간적 비용적 낭비를 없애기 위해 사용

구조체는 값타입이기에 직접적으로 메모리에 접근하므로 낭비를 막을수 있음

c#에서는 크기가 작고 단순한 함수들을 포함하는 선, 컬러 들과 같은 그래픽요소등을 구조체로 정의해두었다.

또한 구조체와 클래스의 다른점은 구조체는 상속자체가 불가능

 

 

[C#] 구조체와 클래스의 차이

클래스와 구조체는 데이터 타입생성기 라는 점에서는 유사하지만, 구조체는 값타입이라는것과 클래스는 참조타입이라는 점에서 차이점이 있다. 구조체를 사용하는이유는 클래스 사용시에 참

vaert.tistory.com

 

유니티 인스펙터 「SerializeField」와 「Serializable」

안녕하세요. 창작자 픽케입니다. 객체 지향 프로그래밍(Object Oriented Programming)이 가지는 중요한 ...

blog.naver.com

 

JsonUtility.ToJson( , true)

flase
true

 

Encoding.UTF8 (가장 많이 쓰는 언어) 

 

또 다른 Json 을 담는방법

예시 ) 친구 LIst를 가져 올때 친구 갯수만큼 친구의 정보를 가져와야하기 때문에

 

- 객체 생성 후 저장 / 다시 불러오기

using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;

//랜덤하게 만들어지는 오브젝트의 정보
[System.Serializable]
public class ObjectInfo
{
    public int type;
    public Transform tr;
}

[System.Serializable]
public class SaveInfo
{
    public int type;
    public Vector3 pos;
    public Quaternion rot;
    public Vector3 scale;
}

[System.Serializable]
public class JsonList
{
    public List<SaveInfo> data;
}

public class ObjectSaveLoad : MonoBehaviour
{
    //만들어진 오브젝트들 담을 변수
    public List<ObjectInfo> objectList = new List<ObjectInfo>();

    void Update()
    {
        //1번키 누르면 랜덤한 모양, 크기, 위치, 회전이 된 오브젝트 만들자.
        if (Input.GetKeyDown(KeyCode.Alpha1))
        { 
            //모양을 랜덤하게 뽑자 (0 ~ 3)
            int type = Random.Range(0, 4);

            //type 모양으로 Gameobject 만들자
            //형변환을 해줘야 함
            GameObject go = GameObject.CreatePrimitive((PrimitiveType)type);
            //크기, 위치, 회전 랜덤하게
            go.transform.localScale = Vector3.one * Random.Range(0.5f, 2.0f);
            //구 안에서의 랜덤한 위치 값을 준다.
            go.transform.position = Random.insideUnitSphere * Random.Range(1.0f, 20.0f);
            go.transform.rotation = Random.rotation;

            //만들어진 오브젝트의 정보를 List에 담자.
            ObjectInfo info = new ObjectInfo();
            info.type = type;
            info.tr = go.transform;

            objectList.Add(info);
        }

        //2번키를 누르면 objectList의 정보를 json으로 저장
        if(Input.GetKeyDown(KeyCode.Alpha2))
        {
            List<SaveInfo> saveInfoList = new List<SaveInfo>();

            //objectList를 기반으로 저장할 정보를 빼오자
            for(int i = 0; i < objectList.Count; i++)
            {
                SaveInfo saveIfo = new SaveInfo();
                saveIfo.type = objectList[i].type;
                saveIfo.pos = objectList[i].tr.position;
                saveIfo.rot = objectList[i].tr.rotation;
                saveIfo.scale = objectList[i].tr.localScale;

                saveInfoList.Add(saveIfo);
            }

            //saveinfoList를 이용해서 JsonData로 만들자.
            JsonList jsonList = new JsonList();
            //키 = 값
            jsonList.data = saveInfoList;
            string jsonData = JsonUtility.ToJson(jsonList, true);
            Debug.Log(jsonData);

            #region 파일 저장 Joson -> byte 저장
            //jsonData를 파일로 저장 new FileStream(파일경로 "/myInfo.txt" 만들겠다. , 읽는/쓰는)
            //using System.IO; 필요
            FileStream file = new FileStream(Application.dataPath + "/objectInfo.txt", FileMode.Create);
            //파일을 열었으면 닫아줘야함.

            //json string 데이터를 byte 배열로 만든다.
            //using System.Text; 필요
            byte[] byteData = Encoding.UTF8.GetBytes(jsonData);
            //byteData 를 file에 쓰자 (0번째부터 byteData길이만큼)
            file.Write(byteData, 0, byteData.Length);

            file.Close();
            #endregion

            //jsonData를 파일로 저장하자

            //Trnasform 저장할 때
            /*{
                "data" : [
                        {
                            "type" : 2,
                            "pos" : {"x":10, "y":20, "z":30),
                            "rot" : {"x":11, "y":22, "z":33),
                            "scale" : {"x":3, "y":3, "z":3},
                        }   
                    ]
            }*/
        }

        //3번 키 누르면 objectInfo.txt에서 데이터를 읽어서 오브젝트를 만들자.
        if(Input.GetKeyDown(KeyCode.Alpha3))
        {
            #region 파일 불러오기 byte -> Json 불러오기
            //myInfo.txt 를 읽어오자 FileMode.Open
            FileStream file = new FileStream(Application.dataPath + "/objectInfo.txt", FileMode.Open);

            //file의 크기만큼 byte배열을 할당한다.
            byte[] byreData = new byte[file.Length];
            //byteData 에 file의 내용을 읽어온다.
            file.Read(byreData, 0, byreData.Length);
            //파일을 닫아주자
            file.Close();
            #endregion

            //byteData를 Json형태의 문자열로 만들자.
            string jsonData = Encoding.UTF8.GetString(byreData);

            //JsonData를 이용해서 JsonList에 Parsing 하자
            JsonList jsonList = JsonUtility.FromJson<JsonList>(jsonData);

            //jsonList.data의 갯수 만큼 오브젝트를 생성하자
            for (int i = 0; i < jsonList.data.Count; i++)
            {
                //type 모양으로 Gameobject 만들자
                //형변환을 해줘야 함
                GameObject go = GameObject.CreatePrimitive((PrimitiveType)jsonList.data[i].type);
                //크기, 위치, 회전 랜덤하게
                go.transform.localScale = jsonList.data[i].scale;
                //구 안에서의 랜덤한 위치 값을 준다.
                go.transform.position = jsonList.data[i].pos;
                go.transform.rotation = jsonList.data[i].rot;
            }
        }
    }
}

팁! 코드 자체로 오브젝트 생성

 

유니티 Json 다른 방법도 있음 (조금 더 어려움)

https://blog.naver.com/PostView.nhn?blogId=pxkey&logNo=221301852856 

 

유니티 「LitJSON」으로 JSON 파일 읽기

안녕하세요. 창작자 픽케입니다. 지난 번 포스팅을 통해, 엑셀(Excel) 데이터를 JSON 데이터로 변환하...

blog.naver.com

 

728x90

'유니티' 카테고리의 다른 글

[유니티] 싱글톤만들기  (0) 2023.08.26
HTTP 통신  (0) 2023.08.24
[유니티] 파일저장  (0) 2023.08.23
[유니티] Joints  (0) 2023.08.17
[유니티] 시네머신  (0) 2023.08.17