MAUIでiOSアプリの開発!

MAUIを使ったiOSアプリの開発についての技術的なメモです。

System.Text.JsonのJsonSerializer.Serializeで例外が発生

System.Text.JsonのJsonSerializer.Serializeを使ってクラスオブジェクトをJson文字列に変換しようとしましたが、以下の例外が発生しました。

System.TypeInitializationException: The type initializer for 'System.Text.Json.JsonSerializer' threw an exception.
 ---> System.MissingMethodException: Method not found: int System.Text.Encodings.Web.TextEncoder.FindFirstCharacterToEncodeUtf8(System.ReadOnlySpan`1)

コード自体は特に難しいことをしていないシンプルな処理です。

調べてみると以下のサイトに対応策がありました。

JsonSerializer throws exception in xamarin.ios - Microsoft Q&A

iOSのプロジェクトファイルをテキストエディタで開き、以下の定義を追加します。

<itemgroup>
    <packagereference include="System.Memory" version="4.5.4">
    <includeassets>none</includeassets>
    </packagereference>
    <packagereference include="System.Buffers" version="4.5.1">
    <includeassets>none</includeassets>
    </packagereference>
</ItemGroup>

これで例外が発生せず、正常に変換できるようになりました。