提问者:小点点

用C#中的动态项反序列化json对象[closed]


我得到了以下json文档:

{
  "name": "bert",
  "Bikes": {
    "Bike1": {
      "value": 1000,
      "type": "Trek"
    },
    "Bike2": {
      "value": 2000,
      "type": "Canyon"
    }
  }
}

可能还有其他自行车,比如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...
        Assert.IsTrue(res.Bikes.Count == 2);
        Assert.IsTrue(res.Bikes[0].Id == "Bike1");
        Assert.IsTrue(res.Bikes[0].Type == "Trek");
        Assert.IsTrue(res.Bikes[0].Value == 1000);
        Assert.IsTrue(res.Bikes[1].Id == "Bike2");
        Assert.IsTrue(res.Bikes[1].Type == "Canyon");
        Assert.IsTrue(res.Bikes[1].Value == 2000);
    }

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

我怎么才能让它工作?

注意:更改输入文档不是一个选项(因为它是一个规范)


共1个答案

匿名用户

您的代码结构没有反映您的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; }
}

person.bikes应更改为dictionary(也不需要bike.id属性),因为bikesjson元素不是数组而是对象。