Home About
C# , .NET , JSON

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

Newtonsoft.Json を使って ndjson をパースします。

System.Text.Json を使って ndjson をパースはこちら

環境

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

$ dotnet --version
5.0.402

MyNdJson プロジェクトの作成

$ dotnet new console --name MyNdJson

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

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

Newtonsoft.Json を追加

$ cd MyNdJson
$ dotnet add package Newtonsoft.Json --version 13.0.1

この段階で MyNdJson.csproj をみると、Newtonsoft.Json が ItemGroup 要素に追加されています。

  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
  </ItemGroup>

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

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

using System;
using System.IO;
using Newtonsoft.Json;

namespace MyNdJson
{
    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 jsonObject = JsonConvert.DeserializeObject(json);
                    Console.WriteLine(jsonObject);
                }
            }
        }
    }
}

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

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

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

$ dotnet run
{
  "name": "hello"
}
{
  "name": "goodby"
}

できました。

デシリアライズ時に Item のインスタンスにする

Newtonsoft.Json では、json を deserialize するときにクラスを指定して、そのクラスのインスタンスを生成することができます。 この機能を使ってみます。

Item クラスを用意。

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

デシリアライズするときにこの Item クラスを指定する。 こんな風に:

Item item = JsonConvert.DeserializeObject<Item>(json);

Program.cs 全体ではこのようになります。

using System;
using System.IO;
using Newtonsoft.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();
                    Item item = JsonConvert.DeserializeObject<Item>(json);
                    Console.WriteLine($"- {item.name}");
                }
            }
        }
    }
}

実行します。

$ dotnet run
- hello
- goodby

できました。

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

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