我有以下 json 文档:
{
"name": "bert",
"Bikes": {
"Bike1": {
"value": 1000,
"type": "Trek"
},
"Bike2": {
"value": 2000,
"type": "Canyon"
}
}
}
Run Code Online (Sandbox Code Playgroud)
可能还有其他自行车,如 Bike3...BikeN。我想反序列化为 c# 对象。问题是在反序列化步骤中,自行车数据完全丢失,导致自行车集合为空。
重现代码:
[Test]
public void FirstCityJsonParsingTest()
{
var file = @"./testdata/test.json";
var json = File.ReadAllText(file);
var res = JsonConvert.DeserializeObject<Person>(json);
Assert.IsTrue(res.Name == "bert");
// next line is failing, because res.Bikes is null...
Assert.IsTrue(res.Bikes.Count == 2);
}
public class Bike
{
public string Id { get; set; }
public int Value { get; set; }
public string Type { get; set; }
}
public class Person
{
public string Name { get; set; }
public List<Bike> Bikes { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题,需要改变使用的模型。但是这里需要进行哪些更改才能正确填充自行车数据?
注意:更改输入文档不是一个选项(因为它是一个规范)
你的代码结构没有反映你的 json,试试这个:
public class Bike
{
public int Value { get; set; }
public string Type { get; set; }
}
public class Person
{
public string Id { get; set; }
public string Name { get; set; }
public Dictionary<string, Bike> Bikes { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Person.Bikes应该更改为Dictionary<string, Bike>(Bike.Id也不需要属性)因为Bikesjson 元素不是数组而是对象。
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |