LoginSignup
0
0

More than 1 year has passed since last update.

C# ( .NET 7 ) - ネストしたハッシュと配列をJSONシリアライズする

Last updated at Posted at 2022-12-01

コード

using System.Text.Json;
using System;
using System.Collections.Generic;

namespace SerializeExtra
{
    public class Body
    {
      public List<User> users { get; set; }
    }

    public class User
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public class Program
    {
        public static void Main()
        {
			
	      var users = new List<User>();
		  users.Add(new User { Name = "Alice",Age = 20 });
	      users.Add(new User { Name = "Bob",Age = 30 });
			
          var body = new Body
            {
				users = users,
            };

            var options = new JsonSerializerOptions { WriteIndented = true };
            string jsonString = JsonSerializer.Serialize(body, options);

            Console.WriteLine(jsonString);
        }
    }
}

結果


{
  "users": [
    {
      "Name": "Alice",
      "Age": 20
    },
    {
      "Name": "Bob",
      "Age": 30
    }
  ]
}

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0