LoginSignup
1
0

More than 3 years have passed since last update.

C#製APIから取得したJSONのKeyを大文字で揃えるには

Posted at

.net core C#でwebAPIを作っているときに, GETしてきたjsonのkeyが大文字小文字入り乱れていて困った。

取得したjson

C#側でこんな感じの構造のデータをDBから取得するAPIを作成した

public class DISK_CONFIG_INFO
{
    [Key, Required]
    public string SERIAL_NO { get; set; }
    public string DISK_NAME { get; set; }
    public string MOUNT_POS { get; set; }
    public decimal? MAX_VOLUME { get; set; }
    public decimal? ROTATE { get; set; }
    public DateTime? INS_DATE { get; set; }
    public DateTime? UPD_DATE { get; set; }
}

これを実際にGETしてみるとこうなってしまった

{
    "Serial_no": "13J0DKSGS",
    "Disk_name": "TOSHIBA DT01ACA300",
    "Mount_pos": "/mnt/sdb",
    "Max_volume": 2793,
    "Rotate": 7200,
    "Ins_date": "2019-04-02T17:02:11",
    "Upd_date": "2019-04-03T15:30:03"
}

何故かjsonのkeyが全て大文字始まりの小文字になっている…

修正方法

結論として, startup.csの中でAddMvc()している箇所でjsonのシリアライズの設定をしてあげればよい

startup.cs
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
  //省略
  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
  //省略
}

これを

startup.cs
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
  //省略
  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                   .AddJsonOptions(opt =>
                  {
                    opt.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
                  });
  //省略
}

こうしてあげる。

結果

再度同じGETメソッドを呼んで見る

{
    "SERIAL_NO": "13J0DKSGS",
    "DISK_NAME": "TOSHIBA DT01ACA300",
    "MOUNT_POS": "/mnt/sdb",
    "MAX_VOLUME": 2793,
    "ROTATE": 7200,
    "INS_DATE": "2019-04-02T17:02:11",
    "UPD_DATE": "2019-04-03T15:30:03"
}

これで大丈夫そうです。

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