Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9551

Utf8JsonでDictionaryのキーにCustom Formatterを利用する

$
0
0

はじめに

.NETでJSONを扱うにあたり、Utf8Jsonというライブラリがあります。

UTF-8ネイティブな.NET用のJSONライブラリにはSystem.Text.Jsonもありますが、参照型を扱う場合にデフォルトコンストラクタが必要なことから、私はUtf8Jsonを使うことがあります。

ここではUtf8Json使う場合に、Dictionaryオブジェクトのキーに組み込み型ではない、自作のクラスや構造体を使う方法を紹介したいと思います。

対象の自作クラス

こんなImmutableなデフォルトコンストラクタを持たないクラスや構造体を、Dictionaryのキーに利用します。

publicreadonlystructEmployeeId{publicEmployeeId(intintValue){IntValue=intValue;}publicintIntValue{get;}}

Custom Formatterを実装する

Utf8Jsonでは独自クラスでJSONのシリアライズを明示的に指定したい場合、IJsonFormatterを実装する必要がありますが、Dictionaryのキーに利用する場合は、IJsonFormatterに追加してIObjectPropertyNameFormatterを実装する必要があります。
EmployeeIdの例では、intのプロパティのみをシリアライズ・デシリアライズしたいので、Formatterを次のように実装します。

このとき、JSONの仕様上、連想配列(Dictionary)のキーは文字列である必要があるため( @ktz_aliasさんに指摘いただきました。ありがとうございました!)、異なるインターフェースIObjectPropertyNameFormatterで変換を実装します。

publicsealedclassEmployeeIdFormatter:IJsonFormatter<EmployeeId>,IObjectPropertyNameFormatter<EmployeeId>{publicvoidSerialize(refJsonWriterwriter,EmployeeIdvalue,IJsonFormatterResolverformatterResolver){writer.WriteInt32(value.IntValue);}publicEmployeeIdDeserialize(refJsonReaderreader,IJsonFormatterResolverformatterResolver){returnnewEmployeeId(reader.ReadInt32());}publicvoidSerializeToPropertyName(refJsonWriterwriter,EmployeeIdvalue,IJsonFormatterResolverformatterResolver){writer.WriteInt32(value.IntValue);}publicEmployeeIdDeserializeFromPropertyName(refJsonReaderreader,IJsonFormatterResolverformatterResolver){returnnewEmployeeId(reader.ReadString());}}

Custom Formatterを利用する

標準のFormatterに追加して、上記のFormatterを利用したい場合、つぎのように実装しましょう。

CompositeResolver.RegisterAndSetAsDefault(newIJsonFormatter[]{newEmployeeIdFormatter()},new[]{StandardResolver.Default});varemployeeNames=newDictionary<EmployeeId,string>{[newEmployeeId(0)]="Steve Jobs",[newEmployeeId(1)]="Bill Gates"};varjsonBytes=Utf8Json.JsonSerializer.Serialize(employeeNames);

これで次のようなJSONが得られます。

{"0":"Steve Jobs","1":"Bill Gates"}

以上です。


Viewing all articles
Browse latest Browse all 9551

Trending Articles