我有一个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[]
。对Id
和Name
字段进行反序列化很简单;但是,如果我想将字符串1789-1797
反序列化为Reign
的实例,其中StartYear
是1789
而EndYear
是1797
,我应该如何去实现它?
答案 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;
}