0
1

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.

API に Request した Body の JSON 文字列を Parse する処理を綺麗に書いてみる

Posted at

Controllerの中でごちゃごちゃやりがちだったので備忘録として残しておく。

InputModelクラスを定義

modelクラスを👇のように定義。

using System.Text.Json;
using System.Text.Json.Serialization;
namespace TestHogeHoge.Models
{
 public class InputModel
    {
        [JsonPropertyName("id")]
        public string Id { get; set; }
        [JsonPropertyName("name")]
        public string Name { get; set; }
        [JsonPropertyName("address")]
        public string Address { get; set; }

        public static InputModel Parse(string json)
        {
            return JsonSerializer.Deserialize<InputModel>(json);
        }
    }
}

各プロパティにはJson時のプロパティとParse先を定義してあげます。
System.Text.JsonのJsonSerializerを使ってデシリアライズしてあげるようにParse()を定義します。

リクエストするときのBodyは定義したModelに合わせてリクエストします。
👇例

{
    "id": "111",
    "name": "hogehoge",
    "address": "hoge address"
}

実際に定義したクラスを使って書いてみると

RequestBody を取得したら StreamReader で読み込んで、
そのままInputModelクラスで定義したParseを実行させます。

var input = await new StreamReader({リクエストしたBody}, Encoding.UTF8).ReadToEndAsync();
var inputData = InputModel.Parse(input);
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?