Home About
C# , .NET , JSON

dotnet コマンドでつくる コンソールアプリケーション, JSON Reader

コンソールアプリケーションを Visual Studio を使わないで、dotnet コマンドとエディタだけでつくる覚え書き。

事前準備

Windows11 WSL 上で作業します。 dotnet 5.0 SDK などはインストール済であることが前提。

MyJson プロジェクトの作成と実行

$ dotnet.exe new console --target-framework-override net5.0 --name MyJson

WSL上で作業しているので、dotnet コマンドには exe をつけて実行する必要あり。

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

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

生成された MyJson/Program.cs には既に Hello, World! を出力するコードが入っています。

using System;

namespace MyJson
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

MyJson プロジェクトを実行して作動を確かめます。

$ cd MyJson 
$ dotnet.exe run
Hello, World!

Hello, World! できました。

Json Reader を試す

コンソールアプリが簡単にできたので、 Utf8JsonReader を使って Jsonファイルを読み込んでパースするコードを書いてみましょう。

詳細はマイクロソフトのドキュメント Utf8JsonReader を確認ください。

パースする対象となる JSONデータを example.json としてカレントディレクトリに作成しておきます。

{"hello":"world"}

この JSON データを Utf8JsonReader を使ってパースするコードを Program.cs に記述します。

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

namespace MyJson
{
    class Program
    {
        static void Main(string[] args)
        {
            var jsonFilePath = "example.json";
            var jsonUtf8Bytes = File.ReadAllBytes(jsonFilePath);

            var options = new JsonReaderOptions
            {
                AllowTrailingCommas = true,
                CommentHandling = JsonCommentHandling.Skip
            };

            var reader = new Utf8JsonReader(jsonUtf8Bytes, options);

            while(reader.Read())
            {
                Console.Write($"<{reader.TokenType}>");

                switch(reader.TokenType)
                {
                    case JsonTokenType.PropertyName:
                    case JsonTokenType.String:
                        {
                            string text = reader.GetString();
                            Console.Write(text);
                            break;
                        }
                }
            }
            Console.WriteLine();
        }
    }
}

それでは実行します。

$ dotnet.exe run
<StartObject><PropertyName>hello<String>world<EndObject>

できました。

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