1
1

More than 3 years have passed since last update.

C#でネスト化したJSONを出力する

Last updated at Posted at 2020-12-08

やりたいこと

何かしらから得たデータをC#上でJSONをネスト化して出力してみました。

環境や使用したライブラリ

  • windows 10 64bit
  • Visual Studio 2019
  • .NET framework 4.7.2
  • System.Text.Json

手順

コンソールアプリケーションの作成

動作確認としてコンソールアプリを作成しました。
1.ファイル→新規作成→プロジェクト→コンソールアプリ(.NET Framework)とクリックして新しいプロジェクトつくります。

image (11).png

2.ソリューションエクスプローラーから「参照」を右クリックで「NuGetパッケージの管理」をクリックします。

2.png

3.「参照」から「text.json」を検索欄に入れてると、「System.Text.Json」がヒットします。そして、これをインストールします。
これで下準備は完了です。

image.png

プログラム

プログラムは下記のようになります。
C#のDictionaryを入れ子にするイメージです。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;

namespace sample_json
{
    class Program
    {
        static void Main(string[] args)
        {
            // 例えば個人データを表すpersonのDictionaryを作成
            var person1 = new Dictionary<string, string>()
            {
                { "name"   ,"John"},
                { "age"   ,"12"},
                { "city"  ,"Tokyo"},
            };

            var person2 = new Dictionary<string, string>()
            {
                { "name"   ,"Ann"},
                { "age"   ,"13"},
                { "city"  ,"Kyoto"},
            };
            // groupは個人データをまとめるためのDictionary
            var group = new Dictionary<int, Dictionary<string, string>>();

            //groupに個人データpersonを追加する
            group.Add(1, person1);
            group.Add(2, person2);

            // Dictionaryをシリアライズ
            var jsonstr = JsonSerializer.Serialize(group);
            // コンソールに出力
            Console.WriteLine("{0}", jsonstr);
            Console.ReadKey();


        }
    }
}


結果

ネストされたJsonを出力することができました。
4.png

おわりに

Dictionaryを入れ子にして、System.Text.Jsonを使うことでネスト化されたJSONを出力することができました。
他にも良い方法があれば教えてください。

参考

C#でJSONを扱う方法。System.Text.Jsonの使い方とは?

1
1
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
1
1