.NET NewtonSoft JSONは別のプロパティ名にマップをデシリアライズします 質問する

.NET NewtonSoft JSONは別のプロパティ名にマップをデシリアライズします 質問する

外部から受け取った次の JSON 文字列があります。

{
   "team":[
      {
         "v1":"",
         "attributes":{
            "eighty_min_score":"",
            "home_or_away":"home",
            "score":"22",
            "team_id":"500"
         }
      },
      {
         "v1":"",
         "attributes":{
            "eighty_min_score":"",
            "home_or_away":"away",
            "score":"30",
            "team_id":"600"
         }
      }
   ]
}

私のマッピングクラス:

public class Attributes
{
    public string eighty_min_score { get; set; }
    public string home_or_away { get; set; }
    public string score { get; set; }
    public string team_id { get; set; }
}

public class Team
{
    public string v1 { get; set; }
    public Attributes attributes { get; set; }
}

public class RootObject
{
    public List<Team> team { get; set; }
}

Attributes 質問は、クラス名とクラス内のattributes フィールド名が気に入らないということですTeam。代わりに、名前を付けTeamScore_フィールド名から削除して適切な名前を付けたいです。

JsonConvert.DeserializeObject<RootObject>(jsonText);

Attributesを に名前変更することはできますTeamScoreが、フィールド名 (クラスattributesTeam) を変更すると、適切に逆シリアル化されず、 が返されますnull。どうすればこれを克服できますか?

ベストアンサー1

Json.NET - ニュートンソフトJsonPropertyAttributeには JSON プロパティの名前を指定できる があるため、コードは次のようになります。

public class TeamScore
{
    [JsonProperty("eighty_min_score")]
    public string EightyMinScore { get; set; }
    [JsonProperty("home_or_away")]
    public string HomeOrAway { get; set; }
    [JsonProperty("score ")]
    public string Score { get; set; }
    [JsonProperty("team_id")]
    public string TeamId { get; set; }
}

public class Team
{
    public string v1 { get; set; }
    [JsonProperty("attributes")]
    public TeamScore TeamScores { get; set; }
}

public class RootObject
{
    public List<Team> Team { get; set; }
}

ドキュメンテーション:シリアル化属性

おすすめ記事