개인 프로젝트

newtonsoft 나한테 왜이러니 도대체

hanui1210 2024. 10. 24. 04:36

newtonsoft 패키지에서 불러올때 

 

이름 => com.unity.nuget.newtonsoft-json

주소 => https://github.com/jilleJr/Newtonsoft.Json-for-Unity.git#upm

git이 같은 드라이브에 깔려있는지도 확인 

 

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

//[CLSCompliant(false)] // 이 클래스를 CLS 비규격으로 표시
public class DataManager : MonoBehaviour
{
    [System.Serializable]
    public class MessageData
    {
        public string name;
        public int face;
        public string message;
    }

    [System.Serializable]
    public class MessageDataList
    {
        public List<MessageData> messageDatas;
    }

    [SerializeField] private Button dataLoadBtn;

    private void Start()
    {
        if (dataLoadBtn != null)
        {
            dataLoadBtn.onClick.AddListener(LoadData);
        }
        else
        {
            Debug.LogError("버튼없어");
        }
    }

    private void LoadData()
    {
        string path = "Data/message_data";
        TextAsset jsonFile = Resources.Load<TextAsset>(path);

        if (jsonFile != null)
        {
            Debug.Log("파일 내용: " + jsonFile.text);

            // JSON 파일을 래퍼 클래스로 감싸서 파싱
            MessageDataList dataList = JsonUtility.FromJson<MessageDataList>("{\"messageDatas\":" + jsonFile.text + "}");

            if (dataList != null && dataList.messageDatas != null)
            {
                foreach (MessageData data in dataList.messageDatas)
                {
                    Debug.Log("Name: " + data.name);
                    Debug.Log("Face: " + data.face);
                    Debug.Log("Message: " + data.message);
                }
            }
            else
            {
                Debug.LogError("JSON 파일의 형식이 올바르지 않습니다.");
            }
        }
        else
        {
            Debug.LogError("파일을 찾을 수 없습니다: " + path);
        }
    }
}