๐ŸŽฎ Unity Study/Unity

[Unity] Json ๋กœ์ปฌ ๋ฐ์ดํ„ฐ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ

ibelieveinme 2023. 8. 24. 02:19
728x90
 

JSON ์ง๋ ฌํ™” - Unity ๋งค๋‰ด์–ผ

JsonUtility ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ Unity ์˜ค๋ธŒ์ ํŠธ๋ฅผ JSON ํฌ๋งท์œผ๋กœ ์ƒํ˜ธ ์ „ํ™˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด JSON ์ง๋ ฌํ™”๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์›น ์„œ๋น„์Šค์™€ ์ƒํ˜ธ์ž‘์šฉํ•˜๊ฑฐ๋‚˜, ๋ฐ์ดํ„ฐ๋ฅผ ํ…์ŠคํŠธ ๊ธฐ๋ฐ˜ ํฌ๋งท์œผ๋กœ ์‰ฝ๊ฒŒ ํŒจํ‚น

docs.unity3d.com

 

json, xml ๋“ฑ ๋‹ค์–‘ํ•œ ํ˜•ํƒœ์˜ ๋ฐ์ดํ„ฐ ํฌ๋งท์ด ์žˆ๋‹ค.

๊ทธ ์ค‘ ๋ณด๊ธฐ๋„ ์ฒ˜๋ฆฌ๋„ ํŽธํ•œ Json ๋ฐ์ดํ„ฐ ํฌ๋งท์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฒ•์„ ์•Œ์•„๋ณด์ž.

 

Json ํฌ๋งท์„ ์ง€์›ํ•˜๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋Š” Unity ์—์„œ ๊ธฐ๋ณธ์œผ๋กœ ์ œ๊ณตํ•˜๋Š” JsonUtility ํด๋ž˜์Šค, Newtonsoft์˜ Newtowsoft.json,  Asset Store์—์„œ ๋‹ค์šด๋ฐ›์„ ์ˆ˜ ์žˆ๋Š” JSON.NET(ํ˜„์žฌ ์ง€์›์ข…๋ฃŒ) ๋“ฑ์ด ์žˆ๋‹ค.

 

๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ๋ณ„๋กœ ์ง€์›ํ•˜๋Š” ๊ธฐ๋Šฅ์ด ๋‹ค๋ฅธ๋ฐ, ๊ฐ„๋‹จํ•œ FromJson, ToJson ๊ธฐ๋Šฅ๋งŒ ์ด์šฉํ•˜๋ ค๋ฉด Unity ๊ธฐ๋ณธ JsonUtility ํด๋ž˜์Šค๋ฅผ ์ด์šฉํ•˜๋ฉด ๋œ๋‹ค.

Newtonsoft์˜ Newtowsoft.json ์€ ์•„๋ž˜์™€ ๊ฐ™์ด ์‚ฌ์šฉํ•˜๋ฉฐ Dictionary ํ˜•ํƒœ์˜ ์ž๋ฃŒ๊ตฌ์กฐ๋„ Serialize์™€ Deserialize ๊ธฐ๋Šฅ์„ ์ง€์›ํ•œ๋‹ค. ๊ทธ์™ธ์—๋„ [JsonProperty("๋ฐ์ดํ„ฐ๋ช…")] ํ‚ค์›Œ๋“œ๋กœ ๋ฐ์ดํ„ฐ ์ด๋ฆ„์„ ๋ฐ”๊ฟ€ ์ˆ˜๋„ ์žˆ๋‹ค.

string ObjectToJson(object obj)
{
    return JsonConvert.SerializeObject(obj);
}

T JsonToOject<T>(string jsonData)
{
    return JsonConvert.DeserializeObject<T>(jsonData);
}
string json = @"{
  'href': '/account/login.aspx',
  'target': '_blank'
}";

Dictionary<string, string> htmlAttributes = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

Console.WriteLine(htmlAttributes["href"]);
// /account/login.aspx

Console.WriteLine(htmlAttributes["target"]);
// _blank
 [JsonProperty("regDt")] public DateTime Date { get; private set; }

 

Resource ํด๋”์— ์žˆ๋Š” json ํŒŒ์ผ์„ ์ฝ์–ด์˜ค๋Š” ์ฝ”๋“œ๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

using System.IO;
using UnityEngine;


namespace Main {

    public class MainManager : MonoBehaviour {

        private const string JSON_FILE = "data.json";

        private void Start() {
            var jsonFile = Resources.Load<TextAsset>(JSON_FILE);
            MainData mainData = JsonUtility.FromJson<MainData>(jsonFile.ToString());
        }
    } 
}

Json online editor ์‚ฌ์ดํŠธ: http://json.parser.online.fr/

 

Json Parser Online

 

json.parser.online.fr

Resource Load ํ•จ์ˆ˜๋“ค: https://docs.unity3d.com/kr/current/ScriptReference/Resources.Load.html

 

Resources-Load - Unity ์Šคํฌ๋ฆฝํŒ… API

Loads the asset of the requested type stored at path in a Resources folder.

docs.unity3d.com

 

728x90