using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;
using System.IO;
public class TangtangMain : MonoBehaviour
{
void Start()
{
TextAsset asset = Resources.Load<TextAsset>("tangtang_data");
//Debug.Log(asset.text);
string json = asset.text;
TangtangData[] datas = JsonConvert.DeserializeObject<TangtangData[]>(json);
foreach (TangtangData data in datas)
{
Debug.LogFormat("{0} {1} {2}", data.id, data.name, data.damage);
}
TangtangInfo[] infoArray = new TangtangInfo[datas.Length];
for (int i = 0; i < datas.Length; i++)
{
TangtangData data = datas[i];
TangtangInfo info = new TangtangInfo(data.damage);
infoArray[i] = info;
}
// 직렬화 시작 (객체 배열 -> 문자열 배열)
string[] serializedJsonArray = new string[infoArray.Length];
for (int i = 0; i < infoArray.Length; i++)
{
serializedJsonArray[i] = JsonConvert.SerializeObject(infoArray[i]);
}
// 파일로 저장
// Application.persistentDataPath: 플랫폼 OS에 따라 경로를 자동으로 설정
string path = Application.persistentDataPath + "/tangtang_info.json";
Debug.Log(path);
File.WriteAllLines(path, serializedJsonArray);
}
}
using System;
public class TangtangData
{
public int id;
public string name;
public string damage;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TangtangInfo
{
public string damage;
public TangtangInfo(string damage)
{
this.damage = damage;
}
}
LINQ를 사용한 JSON 쿼리(Query): LINQ 쿼리를 사용하여 JSON 데이터를 쉽게 쿼리하고 필터링할 수 있습니다.
JSON 스키마(Validation): JSON 데이터가 주어진 스키마에 부합하는지 확인할 수 있습니다.
JSON 파싱(Parsing): JSON 문자열을 해석하고 객체로 변환합니다.
JSON 변환(Transform): JSON 데이터를 다른 형식으로 변환합니다.
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class HelmMain : MonoBehaviour
{
void Start()
{
TextAsset asset = Resources.Load<TextAsset>("helm_data");
string json = asset.text;
Debug.Log(json);
HelmData data = JsonConvert.DeserializeObject<HelmData>(json);
//Debug.Log(data);
Debug.LogFormat("{0} {1} {2} {3}", data.name, data.min_damage, data.max_damage, data.item_type);
//저장
//직렬화 객체 생성
HelmInfo info = new HelmInfo(data.min_damage, data.max_damage);
//직렬화 시작(객체 ->문자열)
string serializedJson = JsonConvert.SerializeObject(info);
//파일로 저장
//Application.persistentDataPath : 플랫폼 OS에 따라 경로를 자동으로 잡아줌
string path = Application.persistentDataPath + "/helm_info.json";
Debug.Log(path);
//문자열을 파일로 저장
File.WriteAllText(path, serializedJson); //경로, 문자열
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelmData
{
public string name;
public int min_damage;
public int max_damage;
public string item_type;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelmInfo
{
public int min_damage;
public int max_damage;
public HelmInfo(int min_damage, int max_damage)
{
this.min_damage = min_damage;
this.max_damage = max_damage;
}
}
실행을 시켜보면
1. 데이터를 문자열을 출력
2. 데이터를 역직렬화 후 데이터를 잘 받고 있는지 확인
3. Helminfo클래스를 메인에서 불러온 후 생성자를 생성한뒤 지정한 경로 위치로 생성후 저장 => 그 위치 출력
jsonviewer 사이트를 이용해서 json을 작성 후 format 누르면 제대로 만들어졌는지 유효성 확인이 된다.
그럼 메모장에 복사 후 이와 같이 저장한 다음 만들어둔 Resources 폴더로 저장
주의점 : 폴더명은 Resources여야 한다.
빈오브젝트 생성 후 스크립트 할당
json이 유니티에 들어갈 때 텍스트에셋으로 바뀜을 확인할 수 있다.
텍스트에셋이 잘 받아졌는지 확인
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft;
using Newtonsoft.Json;
public class Test6Main : MonoBehaviour
{
void Start()
{
TextAsset asset = Resources.Load<TextAsset>("nation_data");
Debug.Log(asset);
}
}
역직렬할 매핑클래스 생성
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NationData
{
public string nation;
public int population;
public string religion;
}
중요한 것은 여기는 비모노이기에 상속받는 : Monobehaviour를 제거
이제 역직렬화를 해주고 출력되는지 확인할 것이다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft;
using Newtonsoft.Json;
public class Test6Main : MonoBehaviour
{
void Start()
{
TextAsset asset = Resources.Load<TextAsset>("nation_data");
//Debug.Log(asset);
string json = asset.text;
Debug.Log(json);
//역직렬화
NationData data = JsonConvert.DeserializeObject<NationData>(json);
Debug.LogFormat("nation : {0}", data.nation);
Debug.LogFormat("population : {0}", data.population);
Debug.LogFormat("religion : {0}", data.religion);
}
}
아틀라스를 만들어서 국기들을 넣어준다.
하다가 무언가 잘못됨을 느꼈다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
using UnityEngine.U2D;
public class NationDataCellView : MonoBehaviour
{
[SerializeField] private SpriteAtlas atlas;
[SerializeField] private Image nation;
[SerializeField] private TMP_Text populationText;
[SerializeField] private TMP_Text religionText;
public void Init(NationData data)
{
this.nation.sprite = atlas.GetSprite(data.nation);
this.populationText.text = string.Format("{0}", data.population);
this.religionText.text = data.religion;
}
}