logo MSJO.kr

System.Text.Json 기본 예제

2019-09-24
MsJ
   

Microsoft의 .NET Core 팀은 인기 있는 라이브러리인 Json.NET(Newtonsoft)을 제거하고 새로운 Json 라이브러리인 System.Text.Json(네임스페이스)을 추가하였다. 아래는 이를 활용한 간단한 기본 예제이다.

// 기본 사용법
class Student{}
JsonSerializer.Serialize(Student.GetList(), options);
JsonSerializer.Deserialize<List<Student>>(jsonString, options);

아래는 콘솔 모드에서 작성한 전체 소스이다.

기본예제 전체소스
using System;
using System.Collections.Generic;
using System.Text.Encodings.Web;
using System.Text.Json;

namespace ConsoleJSON
{
    internal class Program
    {
        private static void Main()
        {
            JsonSerializerOptions options = new()
            {
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                PropertyNameCaseInsensitive = true
            };

            var jsonString = JsonSerializer.Serialize(Student.GetList(), options);
            Console.WriteLine(jsonString);
            Console.WriteLine("----------------------------------------------");

            var students = JsonSerializer.Deserialize<List<Student>>(jsonString, options);

            foreach (var item in students)
            {
                Console.Write($"{item.StudentName} : {item.PhoneNumber.IfEmptyOrNull("xxxx")} : {item.RegDate}");
                Console.WriteLine($" : { item.Address.AddressDetail.IfEmptyOrNull("aaaa")} : { item.Address.ZipCode.IfEmptyOrNull("00000")}");
                Console.WriteLine(@"[AddressList]");
                if (item.AddressList.Count > 0)
                    foreach (var itemList in item.AddressList)
                        Console.WriteLine($"{(char)0x20} {itemList.AddressDetail} : {itemList.ZipCode}");
                else
                    Console.WriteLine(@"NULL");
                Console.WriteLine("----------------------------------------------");
            }
        }
    }

    public class Student
    {
        public string RegDate { get; } = "2021-03-03"; // DateTime.Now.ToString("yyyy-MM-dd");
        public string StudentName { get; set; } = "";
        public string PhoneNumber { get; set; } = "";
        public Address Address { get; set; } = new();
        public List<Address> AddressList { get; set; } = new();

        public static List<Student> GetList()
        {
            return new List<Student>
            {
                new Student { StudentName = "홍길동" },
                new Student { StudentName = "홍길서", PhoneNumber = "1234" },
                new Student { StudentName = "홍길남", PhoneNumber = "4567", Address = new() {AddressDetail = "ABCD", ZipCode ="50000" } },
                new Student { StudentName = "홍길북", PhoneNumber = "8901", Address = new() {AddressDetail = "EFGH", ZipCode ="60000" } },
                new Student { StudentName = "홍홍홍", AddressList = new() { new(){AddressDetail = "abcd", ZipCode ="50001"}, new(){AddressDetail = "efgh", ZipCode ="60001"} } }
            };
        }
    }

    public class Address
    {
        public string AddressDetail { get; set; } = "";
        public string ZipCode { get; set; } = "";
    }

    public static class MyExtensions
    {
        public static string IfEmptyOrNull(this string str, params object[] args)
        {
            return args?.Length > 0 && String.IsNullOrEmpty(str) ? args.GetValue(0).ToString() : str.ToString();
        }
    }
}
Reference

Prεv(Θld)   Nεxt(Nεw)
Content RustLang.kr
Search     RSS Feed     BY-NC-ND