Home About
C# , .NET , JSON

C# .NET で ndjson をパース System.Text.Json 編

前回のエントリーで Newtonsoft.Jsonを使って json のデシリアライズ処理をしたのだが、標準の System.Text.Json で普通にできたのでその方法を記録しておく。

環境

今回は Ubuntu にインストールした .NET 5 の環境でコーディングしています。

$ dotnet --version
5.0.402

MyNdJson プロジェクトの作成

$ dotnet new console --name MyNdJson

この段階での 生成された MyNdJson ディレクトリ以下のプロジェクト構成を確認。

.
└── MyNdJson
    ├── obj/
    ├── Program.cs
    └── MyNdJson.csproj

ndjson データをパースするコードを書く

対象となるファイルを 行ごとに json パースして Item のインスタンスに変換します。

using System;
using System.IO;
using System.Text.Json;

namespace MyNdJson
{
    class Item
    {
        public string name {get; set;}
    }

    class Program
    {
        static void Main(string[] args)
        {
            var options = new JsonSerializerOptions
            {
                IncludeFields = false,
            };

            var filePath = "example.ndjson";

            using(var sr = new StreamReader(filePath))
            {
                while(!sr.EndOfStream)
                {
                    var json = sr.ReadLine();
                    var item = JsonSerializer.Deserialize<Item>(json, options);
                    Console.WriteLine($"- {item.name}");
                }
            }
        }
    }
}

処理対象となる example.ndjson を作成。

{"name": "hello"}
{"name": "goodby"}

それでは実行してみます。

$ dotnet run
- hello
- goodby

できました。

あとは、実際にプロダクションで使うには try catch で IO や JSON の例外をキャッチしてやる必要があるでしょう。

追伸 JsonSerializerOptions IncludeFields オプションについて

このオプションだが、たぶん、シリアライズするときに、シリアライズ対象のクラスのどのフィールドを書き出すか指定できるオプションだと思う。 今回のようにデシリアライズしかしないときはオプションは不要。

つまり、Program.cs は以下のように記述できる。

using System;
using System.IO;
using System.Text.Json;

namespace MyNdJson
{
    class Item
    {
        public string name {get; set;}
    }

    class Program
    {
        static void Main(string[] args)
        {
            var filePath = "example.ndjson";

            using(var sr = new StreamReader(filePath))
            {
                while(!sr.EndOfStream)
                {
                    var json = sr.ReadLine();
                    var item = JsonSerializer.Deserialize<Item>(json);
                    Console.WriteLine($"- {item.name}");
                }
            }
        }
    }
}

詳細は マイクロソフトの該当ページをご覧ください。

Liked some of this entry? Buy me a coffee, please.