[C#] Dictionaryや匿名クラスをJSON文字列に変換する

↓こちらの記事ではクラスオブジェクトとJSONファイルの相互変換について書きました。

が、わざわざJSONの定義に合ったクラスを定義するのはめんどくさいということでDictionaryや匿名クラスをJSON文字列にしてしまおうという記事です。

これである程度、動的にJSON文字列を作ることができます。

デシリアライズ(JSON文字列からDictionary)に関しては結構めんどくさいです。JSONの値の部分がJsonElementとかいう構造体に変換されるのでひと手間必要になります。
こちらの記事にまとめました。

目次

DictionaryをJSON文字列にしてみる

シリアライズにはSystem.Text.Json.JsonSerializer.Serializeメソッドを使います。
DictionaryはキーがString型なら変換できるみたい。
ValueにさらにDictionaryを入れれば階層データも作れます。

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

class Program
{
    public static void Main()
    {
        Dictionary<string, dynamic> dic = new Dictionary<string, dynamic> {
            { "key1", 10 },
            { "key2", 1.25 },
            { "key3", false },
            { "key4", DateTime.Now },
            { "key5", new int[] { 1, 2, 3 } },
            { "key6", new List<string> { "a", "b", "c" } },
            { "key7", new Dictionary<string, int> { { "sub1", 10 }, { "sub2", 20 } }},
        };
        // json文字列に変換
        string jsonstr = JsonSerializer.Serialize(dic, new JsonSerializerOptions { WriteIndented = true });

        // json文字列を表示
        Console.WriteLine(jsonstr);
    }
}

処理を実行するとこんな感じのJSON文字列が出力されます。

{
  "key1": 10,
  "key2": 1.25,
  "key3": false,
  "key4": "2020-06-14T18:09:53.6990036+09:00",
  "key5": [
    1,
    2,
    3
  ],
  "key6": [
    "a",
    "b",
    "c"
  ],
  "key7": {
    "sub1": 10,
    "sub2": 20
  }
}

dynamicってなに?という方はこちらを見てください。

匿名クラスをJSON文字列にしてみる

プロパティ名がJSONのキー名、プロパティの値がJSONの値になる。

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

class Program
{
    public static void Main()
    {
        var ano = new { 
            key1 = 10,
            key2 = 1.25,
            key3 = true,
            key4 = DateTime.Now,
            key5 = new int[] { 1, 2, 3 },
            key6 = new List<string> { "a", "b", "c" },
            key7 = new { sub1 = 10, sub2 = 20 },
        };

        // json文字列に変換
        string jsonstr = JsonSerializer.Serialize(ano, new JsonSerializerOptions { WriteIndented = true });

        // json文字列を表示
        Console.WriteLine(jsonstr);
    }
}
{
  "key1": 10,
  "key2": 1.25,
  "key3": true,
  "key4": "2020-06-14T18:46:21.1917111+09:00",
  "key5": [
    1,
    2,
    3
  ],
  "key6": [
    "a",
    "b",
    "c"
  ],
  "key7": {
    "sub1": 10,
    "sub2": 20
  }
}
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!
目次