一尘不染

.NET NewtonSoft JSON反序列化映射到其他属性名称

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);

我可以重命名AttributesTeamScore,但是如果我更改了字段名(attributesTeam类中),它将无法正确地反序列化并提供给我null。我该如何克服呢?


阅读 326

收藏
2020-07-27

共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; }
}

文档:
序列化属性

2020-07-27