Search code examples
jsonc#-4.0serializationdeserializationjson.net

.NET NewtonSoft JSON deserialize map to a different property name


I have following JSON string which is received from an external party.

{
   "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"
         }
      }
   ]
}

My mapping classes:

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

The question is that I don't like the Attributes class name and the attributes field names in the Team class. Instead, I want it to be named TeamScore and also to remove _ from the field names and give proper names.

JsonConvert.DeserializeObject<RootObject>(jsonText);

I can rename Attributes to TeamScore, but if I change the field name (attributes in the Team class), it won't deserialize properly and gives me null. How can I overcome this?


Solution

  • Json.NET - Newtonsoft has a JsonPropertyAttribute which allows you to specify the name of a JSON property, so your code should be:

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

    Documentation: Serialization Attributes