부트캠프/Unity [ 스파르타 ]

[TIL] 유니티 스파르타 7기 11일차 - Json Write && Read

맏난거 2025. 2. 5. 21:01

VisualStudio Nut 패키지 관리 => Newtonsoft.Json 설치

 

[1] JObject : ( key, value ) pair들을 가질 수 있다.

key : string 값

value : JToken 타입 Premitive타입 ( int, float, string...등등 ), DateTime, TiemSpan, Uri 값 ( JObject, JArray도 삽입가능 )

 

[2] JArray : JSON Array

JObject와 특징이 비슷하지만 key값 없이 value들을 가진다

 

JObject 사용법

// 추가방법
var json = new JObject();
json.Add("id", "Luna");
json.Add("name", "Silver");
json.Add("age", 19);

/*
{
  "id": "Luna",
  "name": "Silver",
  "age": 19
}
*/

JArray 사용법

// 추가방법
var jarray = new JArray();
jarray.Add(1);
jarray.Add("Luna");
jarray.Add(DateTime.Now);

/*
[
  1,
  "Luna",
  "2016-05-21T09:45:27.1049839+09:00"
]
*/

 

< JSON 파일 생성 >

현재 디렉토리 불러오기 && 이전 위치 이동

path = System.IO.Directory.GetCurrentDirectory(); // 현재 디렉토리 위치

// 현재 디렉토리 위치에서 이전 파일경로 이동 방법
path = path.Substring(0, path.IndexOf("\\bin"));
path += "\\config.json"; // 만들어줄 json파일명

 

파일 확인 및 생성

private void CreateFile()
{
    if (!File.Exists(path)) // 현재 경로에 파일이 없으면
    {
        using (File.Create(path)) // 현재 경로에 파일 생성
        {
            Console.WriteLine("파일 생성 완료");
        }
    }
    else
    {
        Console.WriteLine("파일 생성 실패");
    }
}

 

File Write

public void WriteJson()
{
    // 파일이 존재하면 쓰기
    if (File.Exists(path))
    {
        FileWrite();
    }
}

 private void FileWrite()
{
    var json = new JObject();
    json.Add("NAME", "KimChulSu");
    json.Add("AGE", 20);
    json.Add("AVERGE", 82.5);
    
    File.WriteAllText(path, json.ToString());
}

 

File Read

private void ReadJson()
{
    // Json 파일 읽기
    using (StreamReader file = File.OpenText(Path))
    using (JsonTextReader reader = new JsonTextReader(file))
    {
        JObject json = (JObject)JToken.ReadFrom(reader);

        Console.WriteLine($"{(string)json["NAME"].ToString()}");
        Console.WriteLine($"{(int)json["AGE"].ToString()}");
        Console.WriteLine($"{(float)json["AVERGE"].ToString()}");
    }
}