내일배움캠프 Node.js 트랙 81일차
C#에서 Json 파일 사용하기
최종 프로젝트가 진행됨에 따라, 서버와 클라이언트가 동일한 데이터를 공유할 필요성이 생겨났다. Json 파일을 이용하기로 했고, 이를 위한 라이브러리를 찾게 되었다. 물론 깡으로 함수를 만들 수도 있겠지만 C#은 내 주력 언어가 아닌데다가 시간 관계 상 함수를 새로 만드는 건 비효율적이었다.
C#과 유니티 환경을 고려했을 때, 우리가 선택하게 된 라이브러리는 NewtonSoft.Json이었다.
참고 링크 : Read and parse a Json File in C# - Stack Overflow
Read and parse a Json File in C#
How does one read a very large JSON file into an array in c# to be split up for later processing? I have managed to get something working that will: Read the file Miss out headers and only read v...
stackoverflow.com
Json 직렬 변환을 위한 라이브러리 NewtonSoft
NewtonSoft.Json 또는 Json.Net은 닷넷 환경에서 지원되는 JSON 형식 직렬화/역직렬화 라이브러리이다. 다른 라이브러리도 있다곤 하던데 설치에 실패하거나 정확한 사용법을 파악하기가 어려웠다. 반면 NewtonSoft.Json는 유니티 패키지 매니저에서 git URL(com.unity.nuget.newtonsoft-json)을 통해 손쉽게 설치할 수 있었기 때문에 접근성이 매우 좋았다.
사용 예제
해당 라이브러리 사용법에 대해서는 공식 문서와 인터넷 검색의 도움을 많이 받았다.
namespace jsonApp
{
// 1. JSON.NET 설치 (Unity)
// Window - Packet Manager
// git URL - com.unity.nuget.newtonsoft-json 입력
//
using Newtonsoft.Json;
// JSON.NET 를 이용한 Json 예제
class JsonUsingJSONNET
{
public void DoTest()
{
// 2. JSON string 만들기
var p = new Person { Id = 1, Name = "Alex" };
string jsonString = JsonConvert.SerializeObject(p);
System.Diagnostics.Debug.WriteLine(jsonString);
// 3. JSON string으로부터 Object 가져오기
Person pObj = JsonConvert.DeserializeObject<Person>(jsonString);
System.Diagnostics.Debug.WriteLine(pObj.Name);
}
}
}
출처 : JSON.NET - C# 프로그래밍 배우기 (Learn C# Programming)
JSON.NET - C# 프로그래밍 배우기 (Learn C# Programming)
JSON.NET JSON.NET은 .NET에서 JSON을 사용하기 위해 가장 널리 사용되는 오픈 소스이다. JSON.NET은 현재 DLL을 별도로 설치해야 한다는 단점이 있지만, JavaScriptSerializer 나 DataContractJsonSerializer에 비해 훨씬
www.csharpstudy.com
공식 문서 : Introduction
Introduction
Json.NET grew out of projects I was working on in late 2005 involving JavaScript, AJAX, and .NET. At the time there were no libraries for working with JavaScript in .NET, so I made my own. Starting out as a couple of static methods for escaping JavaScript
www.newtonsoft.com
위 사이트의 예제와 설명을 충분히 읽어본 뒤, NewtonSoft.Json의 공식 문서를 열람했다.DeserializeObject<T>
에 대해 검색해보면 아래와 같이 결과가 나온다.
직역해보자면, Json 형식을 특정한 닷넷 타입으로 역직렬화해주는 메서드라고 한다.
공식 문서에서의 설명만으론 정확한 사용법을 알 수 없었기에, 해당 메서드가 사용된 코드를 다시 살펴보게 되었다.Person pObj = JsonConvert.DeserializeObject<Person>(jsonString);
제네릭 타입 자리에 들어갈 Person이라는 객체가 먼저 정의되어야함을 알 수 있다.
데이터 모델 정의하기
예를 들어, 아래와 같은 Json 파일이 있다고 가정해보자.
{
"name": "consumable_item",
"version": "1.0.0",
"data": [
{
"item_id": 28000,
"item_name": "소모품 이름",
"item_type": "Type",
"item_effect": "아이템 효과 설명",
"item_description": "재료 아이템은 20000부터 시작, comsuable은 28000부터 시작",
"hp": 0,
"mp": 0,
"atk": 0,
"def": 0,
"magic": 0,
"speed": 0
},
{
"item_id": 28001,
"item_name": "체력 회복 물약",
"item_type": "consumable",
"item_effect": "HP + 10",
"item_description": "체력을 10 회복 시켜주는 기본적인 물약이다. 익명의 연금술사가 만들었다.",
"hp": 10,
"mp": 0,
"atk": 0,
"def": 0,
"magic": 0,
"speed": 0
},
{
"item_id": 28001,
"item_name": "마나 회복 물약",
"item_type": "consumable",
"item_effect": "MP + 10",
"item_description": "마나를 10 회복 시켜주는 기본적인 물약이다. 익명의 연금술사가 만들었다.",
"hp": 0,
"mp": 10,
"atk": 0,
"def": 0,
"magic": 0,
"speed": 0
}
]
}
DeserializeObject<T>
를 사용하기 위해 JSON 객체의 각 필드를 C# 객체와 속성으로 재정의해야 한다. 일단 공통적으로 name, version, data 필드를 가지고 있으며 data에 할당된 Json 데이터만 가변하는 방식이다.
정리해보자면 아래와 같이 작성해볼 수 있다.
// JsonContainer.cs
using System;
using System.Collections.Generic;
[Serializable]
public class JsonContainer<T>
{
public string name;
public string version;
public List<T> data;
}
// ConsumableItem.cs
using System;
[Serializable]
public class ConsumableItem
{
public int item_id;
public string item_name;
public string item_type;
public string item_effect;
public string item_description;
public int hp;
public int mp;
public int atk;
public int def;
public int magic;
public int speed;
}
위와 동일한 방식으로 정의해둔 C# 파일을 모아두었고, 게임 실행과 동시에 Json을 읽어와 역직렬화하는 코드를 작성하였다.
void Start()
{
JsonFileLoader loader = new JsonFileLoader();
// 단일 JSON 파일 로드
string filePath = Path.Combine(Application.streamingAssetsPath, "Quest.json");
if (!File.Exists(filePath))
{
Debug.LogError($"JSON 파일을 찾을 수 없습니다: {filePath}");
return;
}
var questContainer = loader.ReadJsonFile<JsonContainer<Quest>>(filePath);
if (questContainer == null || questContainer.data == null || questContainer.data.Count == 0)
{
Debug.LogError("JSON 파싱 실패: 데이터가 없습니다.");
return;
}
Debug.Log($"퀘스트 데이터 로드 완료: {questContainer.data[0].quest_id}");
Debug.Log($"퀘스트 데이터 로드 완료: {questContainer.data[1].quest_id}");
Debug.Log($"퀘스트 데이터 로드 완료: {questContainer.data[2].quest_id}");
}
'JS > TIL(Today I Learned)' 카테고리의 다른 글
2025-02-27 <최종 프로젝트 D-15> EC2에서 도커 컨테이너 여러 개 생성하기 (0) | 2025.02.27 |
---|---|
2025-02-26 (0) | 2025.02.26 |
2025-02-24 <최종프로젝트 D-18> 채팅 기능 업그레이드 (0) | 2025.02.24 |
2025-02-21 <최종 프로젝트 D-21> (0) | 2025.02.21 |
2025-02-20 <TCP와 UDP> (0) | 2025.02.20 |
댓글