지난 글에 이어서 작성
using UnityEngine;
using Newtonsoft.Json;
using NUnit.Framework;
using System.Collections.Generic;
public class NewtonsoftJsonExample : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
//JsonTestClass jTest1 = new JsonTestClass();
//string jsonData = JsonConvert.SerializeObject(jTest1);
//Debug.Log(jsonData);
//JsonTestClass jTest2 = JsonConvert.DeserializeObject<JsonTestClass>(jsonData);
//jTest2.Prinnt();
//GameObject obj = new GameObject();
//obj.AddComponent<TestMono>();
//Debug.Log(JsonConvert.SerializeObject(obj.GetComponent<TestMono>()));
JsonVector jsonVector = new JsonVector();
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
Debug.Log(JsonConvert.SerializeObject(jsonVector, settings));
}
// Update is called once per frame
void Update()
{
}
}
public class JsonVector
{
public Vector3 vector3 = new Vector3(3, 3, 3);
}
public class JsonTestClass
{
public int i;
public float f;
public bool b;
public string str;
public int[] iArray;
public List<int> iList = new List<int>();
public Dictionary<string, float> fDictionary = new Dictionary<string, float>();
public IntVector2 iVector;
public JsonTestClass()
{
i = 10;
f = 99.9f;
b = true;
str = "JSON Test String";
iArray = new int[] { 1, 1, 2, 3, 5, 8, 12, 21, 34, 55 };
for (int idx = 0; idx < 5; idx++)
{
iList.Add(2 * idx);
}
fDictionary.Add("PIE", Mathf.PI);
fDictionary.Add("Epsilon", Mathf.Epsilon);
fDictionary.Add("Sqrt(2)", Mathf.Sqrt(2));
iVector = new IntVector2(3, 2);
}
public void Prinnt()
{
Debug.Log("i = " + i);
Debug.Log("f = " + f);
Debug.Log("b = " + b);
Debug.Log("str = " + str);
for (int idx = 0; idx < iArray.Length; idx++)
{
Debug.Log(string.Format("iArray[{0}] = {1}", idx, iArray[idx]));
}
for (int idx = 0; idx < iList.Count; idx++)
{
Debug.Log(string.Format("iList[{0}] = {1}", idx, iList[idx]));
}
foreach (var data in fDictionary)
{
Debug.Log(string.Format("iDictionary[{0}] = {1}", data.Key, data.Value));
}
Debug.Log("iVector = " + iVector.x + ", " + iVector.y);
}
public class IntVector2
{
public int x;
public int y;
public IntVector2(int x, int y)
{
this.x = x;
this.y = y;
}
}
}
//코드를 이렇게 작성
using UnityEngine;
public class JsonUtilityExample : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
JsonTestClass jTest1 = new JsonTestClass();//새 Json을 생성해줌
string jsondata = JsonUtility.ToJson(jTest1);//생성한 Json을 문자화
Debug.Log(jsondata);//콘솔에 출력
JsonTestClass jTest2 = JsonUtility.FromJson<JsonTestClass>(jsondata);//Json을 명시적으로 오브젝트화
jTest2.Prinnt();//오브젝트화 하여 출력시킴
}
// Update is called once per frame
void Update()
{
}
}
제이슨 유틸리티의 장점은 기본적인 데이터 타입과 배열, 리스트에 대한 시리얼 라이즈만 지원하며
딕셔너리는 지원하지 않음
(딕셔너리는 숫자에서 배열을 받아오는게 아니라 key 값으로 배열을 가져오는 값
잊어먹으면 검색 할 것!)
그리고 또 문제가 있는데 직접 생성한 클레스는 못 불러올 수 있으므로
[System.Serializable]//Json에서 사용하게 추가 작성해줌
public class IntVector2
{
public int x;
public int y;
public IntVector2(int x, int y)
{
this.x = x;
this.y = y;
}
}
//맨 위의 스크립트에서 클래스 부분
[System.Serializable] << 클레스 위에 스크립트를 입력해주면 된다
유니티의 json이 지원하는 특수 기능
유니티의 외부라이브러리는 지원하지 않아 시리얼 라이즈 할때 자기 참조가 계속 발생함
특히 Vector3가 매우 심하고 방향이나 위치를 저장하기 때문에 캐릭터의 마지막 위치를 저장하는데 사용된다
그런데 이게 Json에서는 까다롭다
왜나면 필요하지 않는 정보까지 저장하기 때문
void Start()
{
JsonVector jVector = new JsonVector();
string jsonData = JsonUtility.ToJson(jVector);
Debug.Log(jsonData);
}
//클래스를 따로 넣어서 실행
모노비헤어비어를 상속받는 클레스의 오브젝트 시리얼 라이즈
using UnityEngine;
public class JsonUtilityExample : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
GameObject obj = new GameObject();
obj.AddComponent<TestMono>();
string jsonData = JsonUtility.ToJson(obj.GetComponent<TestMono>());//<<GET컴포넌트를 꼭사용
Debug.Log(jsonData);
}
}
위에서 GetComponent 클레스를 반드시 사용할 것!
다시 모노비헤어비어를 상속받는 클레스를 다시 오브젝트로!
using UnityEngine;
public class JsonUtilityExample : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
JsonUtility.FromJson<TestMono>(jsonData);
}
}
using UnityEngine;
public class JsonUtilityExample : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
GameObject obj = new GameObject();
var test1 = obj.AddComponent<TestMono>();//테스트를 위해 var로 임시로 만들고 덮어씌움
test1.i = 100;
test1.v3 /= 10;
string jsonData = JsonUtility.ToJson(obj.GetComponent<TestMono>());
Debug.Log(jsonData);
GameObject obj2 = new GameObject();
JsonUtility.FromJsonOverwrite(jsonData, obj2.AddComponent<TestMono>());
}
}
이렇게 작성하면 Json으로 이미 만들어진 값을 덮어 씌우게 되는데 이렇게 하여서 게임의 세이브와 로드 기능을 구현할 수 있다
'유니티 & Json' 카테고리의 다른 글
Json으로 세이브 파일 만들기, 로드 (0) | 2024.10.24 |
---|---|
유니티와 JSON주의 할 점 (0) | 2024.10.24 |
유니티에서 JSON사용하기 (2) | 2024.10.22 |
엑셀로 데이터 테이블 만들고 JSON으로 가공하기 (0) | 2024.08.17 |