json - .NET NewtonSoft JSON 反序列化映射到不同的属性名称

标签 json c#-4.0 serialization deserialization json.net

我有以下从外部方收到的 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 class nameattributes field names Team 类。相反,我希望将其命名为 TeamScore 并从字段名称中删除 _ 并给出正确的名称。

JsonConvert.DeserializeObject<RootObject>(jsonText);

我可以将 Attributes 重命名为 TeamScore,但如果我更改字段名称(Team 中的 attributes class),它不会正确反序列化并给我 null。我该如何克服这个问题?

最佳答案

Json.NET - Newtonsoft有一个 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; }
}

文档: Serialization Attributes

关于json - .NET NewtonSoft JSON 反序列化映射到不同的属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15915503/

相关文章:

java - ObjectMapper java.lang.NoSuchMethodError : com. fasterxml.jackson.core.JsonFactory.requiresPropertyOrdering()Z

php - 在 jQuery 中使用 AJAX 访问信息并将数据从 PHP 传递到 JSON

c#-4.0 - 如何使用 Dapper ORM 获取子对象的值?

json - 如何在没有映射的情况下将 JSON 反序列化为 Swift 中的对象

c# - 仅使用 xml 文件的部分内容

.net - WCF 自定义序列化程序

php - 当我在 JavaScript 中告诉它时,While 循环不会结束

javascript - 如何遍历 DataTable 中的特定列?

jquery - Openseadragon 中的 Canvas 右键单击

linux - 如何在 linux 中运行 c#4.0(visual studio 2010) windows 桌面应用程序?