JenonD JenonD - 7 months ago 90
JSON Question

.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 "Attribute class" and the "attributes field name" in the Team class. Instead, I want it to be named as "TeamScore" and also to remove "_" from the field names and give proper names.

JsonConvert.DeserializeObject<RootObject>(jsonText);


I can change the "Attribute" class to a "TeamScore", but if I change the filed name (attributes in the Team Class), it won't deserialize properly and gives me null. How can I overcome this?

Answer Source

Json.NET has a JsonPropertyAttribute which allows you to specify name of 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