Deserialize JSON not working with JSON.NET

醉酒当歌 提交于 2019-12-05 06:19:45

I think, with your current JSON, you are describing that Skill contains a collection, not Skills. Try this JSON instead:

        "Skills": [
            {
                "@Id": "1",
                "@Name": "Developer"
            },
            {
                "@Id": "2",
                "@Name": "Tester"
            }
        ]

The same thing applies to how you are defining the Persons collection.

EDIT:

This test passes for me:

    [TestFixture]
    public class JSONTester
    {
        [Test]
        public void Json_deserialize()
        {
            var json = @"{
    ""?xml"": {
        ""@version"": ""1.0"",
        ""@encoding"": ""utf-8""
    },
    ""Persons"": {
        ""Person"": [{
            ""@Id"": ""1"",
            ""@Name"": ""John"",
            ""@Surname"": ""Smith""         
        },
        {
            ""@Id"": ""2"",
            ""@Name"": ""John"",
            ""@Surname"": ""Smith"",
            ""Skills"": {
                ""Skill"": [{
                    ""@Id"": ""1"",
                    ""@Name"": ""Developer""                    
                },
                {
                    ""@Id"": ""2"",
                    ""@Name"": ""Tester""
                }]
            }
        }]
    }
}";

            var persons = JsonConvert.DeserializeObject<RootObject>(json);

            Assert.AreEqual(persons.Persons.Person[1].Skills.Skill.Count, 2);

        }

        public class RootObject
        {
            public Xml xml { get; set; }
            public Persons Persons { get; set; }
        }

        public class Xml
        {
            public string version { get; set; }
            public string encoding { get; set; }
        }

        public class Persons
        {
            public List<Person> Person { get; set; }
        }
        public class Skill
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

        public class Skills
        {
            public List<Skill> Skill { get; set; }
        }

        public class Person
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Surname { get; set; }
            public Skills Skills { get; set; }
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!