C#

json 이용해서 객체 직렬화/역직렬화 하기

s0002 2023. 1. 12. 21:20
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.IO;

namespace Study11
{
    class App
    {
        //생성자
        public App()
        {
            //객체를 만들고 직렬화 해서 json 형식(문자열) 파일로 저장

            //1. 객체 만들기
            Item item0= new Item("장검",10);

            //2. 직렬화 하기:아이템 객체 넣어주면 json 문자열 반환
            string json0 = JsonConvert.SerializeObject(item0);

            Console.WriteLine(json0); //잘 들어갔나 확인 
            //{"name":"장검","damage":10} 출력

            //3. File.WriteAllText: 새 파일을 만들고
            //파일에 내용을 쓴 다음 파일을 닫는다.
            //파일이 이미 있으면 덮어쓴다
            File.WriteAllText("my_item.json", json0);



            //역직렬화 - 문자열을 객체로 만든다

            //1. File.ReadAllText: 텍스트 파일을 열고
            //파일의 모든 텍스트를 문자열로 읽은 다음 파일을 닫는다
            string json1 = File.ReadAllText("./my_item.json"); 

            //2. 역직렬화 하기
            //반환하는 값의 타입은 읽어들인 객체의 클래스 타입
            item0 = JsonConvert.DeserializeObject<Item>(json1);

            Console.WriteLine(item0);
            Console.WriteLine("name:{0}, damage:{1}", item0.name, item0.damage);
        }
    }
}

'C#' 카테고리의 다른 글

객체 한 개 직렬화/역직렬화  (0) 2023.01.12
linq 연습  (0) 2023.01.12
대리자  (0) 2023.01.11
프로퍼티(Property)/Hashtable/구조체/인터페이스/다형성/오버라이딩  (0) 2023.01.10
2차원 배열  (0) 2023.01.10