C#/C# 교과서

[C# 교과서] 59. XML과 JSON 맛보기

서니션 2023. 2. 11. 18:00
728x90
반응형

XElement 클래스를 사용하여 XML 요소를 생성하거나 사용하기

XElement 클래스는 XML 요소를 생성하거나 담을 수 있는 그릇

using System;
using System.Linq;
using System.Xml.Linq;

class XElementDemo
{
    static void Main()
    {
        // XML 요소 생성
        XElement category = new XElement("Menus",
            new XElement("Menu", "책"),
            new XElement("Menu", "강의"),
            new XElement("Menu", "컴퓨터")
        );
        Console.WirteLine(category);
        
        // XML 요소 가공
        XElement newCategory = new XElement("Menus",
            from node in category.Elements()
            where node.Value.ToString().Length >= 2
            select node
        );
        Console.WriteLine(newCategory);
    }
}

XML 데이터를 다루는 클래스 중에서 XElement 클래스를 사용하여 XML 데이터를 만들고,

XML 데이터에 LINQ를 사용하여 XML 요소를 가공


JSON 데이터 직렬화 및 역직렬화하기

JSON이란?

JavaScript Object Notation 데이터는 최근 프로그래밍에서 많이 사용하는 데이터 구조

 

직렬화 : C# 개체를 JSON 데이터로 변환

역직렬화 : JSON 데이터를 C# 개체로 변환

 

JSON 직렬화 및 역직렬화를 편리하게 사용할 수 있는 API는 JSON.NET 이름의 다음 URL에 있는 NuGet 패키지를 활용

https://www.nuget.org/packages/Newtonsoft.Json/

 

Newtonsoft.Json 13.0.2

Json.NET is a popular high-performance JSON framework for .NET

www.nuget.org

 

먼저 JSON.NET을 사용하려면 Newtonsoft.Json.dll 파일을 Nuget 패키지 관리지 사용하여 참조해야 함

#r "Newtonsof.Json"

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

public class Shirt
{
    public string Name { get; set; }
    public DateTime Created { get; set; }
    public List<string> Sizes { get; set; }
}

public class JsonConvertDemo
{
    static void Main()
    {
        //[1] 직렬화(Serialize) 데모
        Shirt shirt1 = new Shirt
        {
            Name = "Red Shirt",
            Created = new DateTime(2020, 01, 01),
            Sizes = new List<string> { "Small" }
        };
        string json1 = JsonConvert.SerializeObject(shirt1, Formatting.Indented);
        Console.WriteLine(json1);

        //[2] 역직렬화(Deserialize) 데모
        string json2 = @"{
            'Name': 'Black Shirt',
            'Created': '2020-12-31T00:00:00',
            'Sizes': ['Large']
        }";
        Shirt shirt2 = JsonConvert.DeserializeObject<Shirt>(json2);
        Console.WriteLine($"{shirt2.Name} - {shirt2.Created}");
    }
}

 

728x90
반응형