728x90

 구조체를 json 문자열로 관리하는 코드예시입니다.

구조체를 문자열로 만들고 추가 및 제거, 수정하는 코드입니다.

using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Linq;

public class JsonCrudExample
{
    private const string FilePath = "people.json";

    public static void CreatePerson(Person person)
    {
        List<Person> people = ReadPeople();

        people.Add(person);
        SavePeople(people);
    }

    public static List<Person> ReadPeople()
    {
        if (!File.Exists(FilePath))
        {
            return new List<Person>();
        }

        using (StreamReader file = File.OpenText(FilePath))
        {
            JsonSerializer serializer = new JsonSerializer();
            return (List<Person>)serializer.Deserialize(file, typeof(List<Person>));
        }
    }

    public static void UpdatePerson(Person updatedPerson)
    {
        List<Person> people = ReadPeople();

        var existingPerson = people.FirstOrDefault(p => p.Id == updatedPerson.Id);
        if (existingPerson != null)
        {
            existingPerson.Name = updatedPerson.Name;
            existingPerson.Age = updatedPerson.Age;
            SavePeople(people);
        }
    }

    public static void DeletePerson(int id)
    {
        List<Person> people = ReadPeople();

        var personToRemove = people.FirstOrDefault(p => p.Id == id);
        if (personToRemove != null)
        {
            people.Remove(personToRemove);
            SavePeople(people);
        }
    }

    private static void SavePeople(List<Person> people)
    {
        using (StreamWriter file = File.CreateText(FilePath))
        {
            JsonSerializer serializer = new JsonSerializer();
            serializer.Serialize(file, people);
        }
    }
}
728x90
Posted by kjun.kr
,