こんな感じの JSON をこんなモデルクラスに嵌めるとき、残念ながら一部の値は null になってしまう。
取得した JSON
{ "id": "hogeId", "ext": "hogeExt", "height": 768, "width": 1024, "source_url": "http://hoge" }
C# モデルクラス
public string Id { get; set; } public string Ext { get; set; } public string Height { get; set; } public string Width{ get; set; } public string SourceUrl { get; set; }
ここではモデルクラスの SourceUrl
の値が null になってしまう。元の JSON のキー名がアンダースコアで区切られているためで、sourceUrl
にうまく入ってくれない。(大文字小文字はとくに問題ない?)
こういうときには各プロパティの属性に JSON のキー名を指定すればよい。
[JsonProperty("id")] public string Id { get; set; } [JsonProperty("ext")] public string Ext { get; set; } [JsonProperty("height")] public string Height { get; set; } [JsonProperty("width")] public string Width { get; set; } [JsonProperty("source_url")] public string SourceUrl { get; set; }
JSON の source_url
とプロパティ SourceUrl
が紐付けられたので、期待した値が格納される。
自分で生成した JSON を受け取るならばそちらを直した方が手間が掛からないけれど、他サービスの API 叩くときにそういう訳にはいかないので。