小编ber*_*rtt的帖子

使用c#中的动态项反序列化json对象

我有以下 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; } …
Run Code Online (Sandbox Code Playgroud)

c# json.net

0
推荐指数
1
解决办法
72
查看次数

标签 统计

c# ×1

json.net ×1