22
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#でJSONを扱うときはSystem.Text.Jsonを使う

Last updated at Posted at 2019-11-30

はじめに

「C# JSON」とかで検索するとDataContractJsonSerializerかJson.NETを解説した記事がよくヒットします。
しかし、DataContractJsonSerializer クラスのページを見ると「JSON へのシリアル化と JSON からの逆シリアル化を含むほとんどのシナリオでは、system.string名前空間のツールを使用することをお勧めします。」と書いてるので、使えるならこっちを使った方がよいと思います。

使用条件

.NET での JSON のシリアル化-概要から抜粋。

.NET Core 3.0の場合はデフォルトで入ってます。
.NET Standard 2.0以降、.NET Framework 4.6.1以降、.NET Core 2.0以降はSystem.Text.Jsonのnugetパッケージを入れることで使えるようになります。

使用方法

.NET で JSON をシリアル化および逆シリアル化する方法から抜粋。

シリアライズ

System.Text.Json名前空間をusingして次のようなコードでシリアライズできます。
SerializeToUtf8BytesというUTF8を高速で処理できるメソッドもあります。

string jsonString = JsonSerializer.Serialize(serializeObj);

[JsonIgnore]を使用してシリアライズしたくないプロパティを除外することができます。
下の例では自動実装じゃないプロパティを除外しています。

class Test
{

    public double Property1 { get; set; }

    // 自動実装ではないプロパティを除外する。
    [JsonIgnore]
    public double Property2
    {
        get => Property1 * 2;
        set => Property1 = value / 2;
    }

}

デシリアライズ

デシリアライズは下記のコードで行えます。
ジェネリックなのでキャストの必要が無いところがいいですね。

TestClass deserializeObj = JsonSerializer.Deserialize<TestClass>(jsonString);

メリット

  • 基本的にジェネリックメソッドなのでキャストやtypeofが必要ない。
  • [DataContract]みたいなアノテーションが不要。

参考

文中でも取り上げましたが再度まとめ。

22
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?