1
0

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 3 years have passed since last update.

【C#】ModelをJSONシリアライズしたい

Posted at

シリアライズ

ModelをJSONにシリアライズしたいとき、あると思います。
JsonSerializerOptionsをいじると整形したりnull項目を非表示にしたりできます。

CS
Model model = new Model 
{ 
    TemperatureCelsius = 1,
    Summary = "No.1",
};

var optionsUTF8 = new JsonSerializerOptions
{
    // すべての null 値プロパティを除外
    IgnoreNullValues = true,
    // 文字コードの設定
    Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
    // 整形出力を行う
    WriteIndented = true
};

var serialize = JsonSerializer.Serialize(model, optionsUTF8);
出力結果
{
  "TemperatureCelsius": 1,
  "Summary": "No.1"
}

おまけ

拡張メソッドにしておくとちょっと便利。

CS
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;

public static class JsonUtility
{
    // 拡張メソッドにしておくとちょっと便利
    public static string ToJson<T>(this T model)
    {
        var optionsUTF8 = new JsonSerializerOptions
        {
            // すべての null 値プロパティを除外
            IgnoreNullValues = true,
            // 文字コードの設定
            Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
            // 整形出力を行う
            WriteIndented = true
        };

        return JsonSerializer.Serialize(model, optionsUTF8);
    }
}
呼び出し方
var serialize = model.ToJson();
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?