.NET NewtonSoft JSON 反序列化映射到不同的属性名称 [英] .NET NewtonSoft JSON deserialize map to a different property name

查看:33
本文介绍了.NET NewtonSoft JSON 反序列化映射到不同的属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下来自外部方的 JSON 字符串.

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

我的映射类:

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团队 类.相反,我希望将其命名为 TeamScore 并从字段名称中删除 _ 并提供适当的名称.

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

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

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?

推荐答案

Json.NET 有一个 JsonPropertyAttribute 允许您指定 JSON 属性的名称,因此您的代码应该是:

Json.NET 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

这篇关于.NET NewtonSoft JSON 反序列化映射到不同的属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆