将字符串反序列化为具有2个uint字段的结构

时间:2019-04-17 15:21:26

标签: c# json json.net

我有一个JSON文档,其中包含有关所有美国总统的数据。这是一个示例:

{
    "id": 1,
    "name": "George Washington",
    "years": "1789-1797"
}

我已经定义了一个类President,如下所示:

public class President
{
    [JsonProperty("id")] public int Id;
    [JsonProperty("name")] public string Name;
    [JsonProperty("years")] public Reign Reign;
}

这是我的Reign结构:

public struct Reign
{
    public uint StartYear;
    public uint EndYear;
}

我想将JSON文档反序列化为President[]。对IdName字段进行反序列化很简单;但是,如果我想将字符串1789-1797反序列化为Reign的实例,其中StartYear1789EndYear1797,我应该如何去实现它?

1 个答案:

答案 0 :(得分:3)

这种方式:

class Program
{
    static void Main(string[] args)
    {
        string json = "{ \"id\": 1, \"name\": \"George Washington\", \"years\": \"1789-1797\" }";
        President president = JsonConvert.DeserializeObject<President>(json);
    }
}

public class President
{
    [JsonProperty("id")] public int Id;
    [JsonProperty("name")] public string Name;
    [JsonProperty("years")] private string _reign
    {
        set
        {
            string[] years = value.Split('-');
            Reign = new Reign
            {
                StartYear = uint.Parse(years[0]),
                EndYear = uint.Parse(years[1])
            };
        }
    }
    public Reign Reign;
}

public struct Reign
{
    public uint StartYear;
    public uint EndYear;
}