본문 바로가기
카테고리 없음

C#에서 JSON 파일 읽기, 쓰기, 수정하는 간단한 방법

by tasiklee 2025. 2. 16.

JSON(JavaScript Object Notation)은 가볍고 유연한 데이터 포맷으로, 그만큼 다양한 프로그래밍 언어에서 널리 사용되고 있습니다!

C#에서도 JSON을 활용하여 데이터를 저장, 읽기, 수정하는 작업을 쉽게 할 수 있는데요,

이번 글에서는 C#에서 JSON 파일을 불러와 읽고 쓰고 수정하는 방법을 예제 코드와 함께 설명하겠습니다.


🟢 1. JSON을 다루는 방법

C#에서 JSON을 다룰 때 가장 많이 사용되는 라이브러리는 Newtonsoft.Json (Json.NET)입니다.

✅ JSON을 다루는 대표적인 라이브러리

  1. Newtonsoft.Json → 가장 널리 사용되며, 직렬화/역직렬화 기능이 강력함 (추천)
  2. System.Text.Json → .NET Core부터 기본 제공되는 JSON 처리 라이브러리

이번 글에서는 가장 널리 사용되고 있는 Newtonsoft.Json을 활용한 JSON 처리 방법을 다루겠습니다.


🟡 2. Newtonsoft.Json 설치

Newtonsoft.Json은 NuGet 패키지를 통해 설치할 수 있습니다.

✅ 1) NuGet 패키지 설치

  1. Visual Studio를 실행합니다.
  2. 도구(Tools) → NuGet 패키지 관리자 → 패키지 관리자 콘솔을 엽니다.
  3. 아래 명령어를 실행하여 Newtonsoft.Json을 설치합니다.
Install-Package Newtonsoft.Json

설치가 완료되면 using Newtonsoft.Json;을 사용하여 JSON을 다룰 수 있습니다.


🔵 3. JSON 파일 읽기 (Deserialize)

✅ 1) JSON 파일 예제

우선, 다음과 같은 data.json 파일을 준비합니다.

{
  "Id": 1,
  "Name": "김철수",
  "Age": 25,
  "Email": "chulsoo@example.com"
}

 


✅ 2) JSON 파일을 읽어와 객체로 변환

아래 코드는 data.json 파일을 읽고, JSON 데이터를 C# 객체로 변환하는 방법인데요, 한번 들여다 볼게요~!

using System;
using System.IO;
using Newtonsoft.Json;

class Program
{
    static void Main()
    {
        string filePath = "data.json";
        ReadJsonFile(filePath);
    }

    static void ReadJsonFile(string filePath)
    {
        if (!File.Exists(filePath))
        {
            Console.WriteLine("파일이 존재하지 않습니다.");
            return;
        }

        string json = File.ReadAllText(filePath);
        Person person = JsonConvert.DeserializeObject<Person>(json);

        Console.WriteLine($"ID: {person.Id}");
        Console.WriteLine($"이름: {person.Name}");
        Console.WriteLine($"나이: {person.Age}");
        Console.WriteLine($"이메일: {person.Email}");
    }
}

// JSON 데이터를 저장할 C# 클래스
class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

📌 File.ReadAllText(filePath) : JSON 파일을 문자열로 읽어옴
📌 JsonConvert.DeserializeObject<T>() : JSON 데이터를 C# 객체로 변환

위와 같이 실행하면 JSON 데이터가 객체로 변환되어 출력 되는 것을 확인 하실 수 있습니다!


🟠 4. JSON 파일 생성 및 쓰기 (Serialize)

이제 C# 객체를 JSON 파일로 저장하는 방법을 알아보도록 하겠습니다!

✅ 1) C# 객체를 JSON 파일로 저장

using System;
using System.IO;
using Newtonsoft.Json;

class Program
{
    static void Main()
    {
        string filePath = "output.json";
        WriteJsonFile(filePath);
        Console.WriteLine("JSON 파일이 생성되었습니다.");
    }

    static void WriteJsonFile(string filePath)
    {
        Person person = new Person
        {
            Id = 2,
            Name = "이영희",
            Age = 30,
            Email = "younghee@example.com"
        };

        string json = JsonConvert.SerializeObject(person, Formatting.Indented);
        File.WriteAllText(filePath, json);
    }
}

class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

📌 JsonConvert.SerializeObject(person, Formatting.Indented) : C# 객체를 JSON 형식으로 변환
📌 File.WriteAllText(filePath, json) : JSON 데이터를 파일로 저장

위 코드를 실행하면 "output.json" 파일이 생성되며, JSON 형식으로 저장됩니다.


🔥 5. JSON 파일 수정

기존 JSON 파일에서 특정 값을 변경하는 방법을 알아보도록 할게요 ~!

✅ 1) JSON 파일 수정

using System;
using System.IO;
using Newtonsoft.Json;

class Program
{
    static void Main()
    {
        string filePath = "data.json";
        UpdateJsonFile(filePath);
        Console.WriteLine("JSON 파일이 수정되었습니다.");
    }

    static void UpdateJsonFile(string filePath)
    {
        if (!File.Exists(filePath))
        {
            Console.WriteLine("파일이 존재하지 않습니다.");
            return;
        }

        string json = File.ReadAllText(filePath);
        Person person = JsonConvert.DeserializeObject<Person>(json);

        // 데이터 수정
        person.Age = 27;
        person.Email = "updated@example.com";

        // 다시 JSON 파일로 저장
        json = JsonConvert.SerializeObject(person, Formatting.Indented);
        File.WriteAllText(filePath, json);
    }
}

class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

📌 person.Age = 27; : 기존 객체의 데이터를 수정
📌 JsonConvert.SerializeObject(person, Formatting.Indented) : 수정된 객체를 JSON 형식으로 변환 후 저장

이런식으로 작성 후 실행하게 되면JSON 파일이 수정됩니다!


✅ 6. 정리

기능코드 설명

JSON 읽기 JsonConvert.DeserializeObject<T>() 사용
JSON 쓰기 JsonConvert.SerializeObject(obj, Formatting.Indented) 사용
JSON 수정 기존 JSON 파일을 읽고 수정 후 다시 저장
파일 입출력 File.ReadAllText(), File.WriteAllText() 사용

🚀 Newtonsoft.Json을 활용하면 C#에서 JSON 데이터를 쉽게 읽고, 저장하고, 수정할 수 있습니다.
실제 프로젝트에서도 JSON을 활용하면 데이터 저장 및 교환이 훨씬 간편해집니다! 😊