dynamic关键字的使用

https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonConvert.htm

在使用DeserializeObject函数进行转换的时候,会自动处理,如果和T匹配,就会转换好。

如果类型不匹配,也不会报错的。

  public class Person
        {
            public string Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Email { get; set; }
        }
        public class People
        {
            public string Gender { get; set; }
        }

        /// <summary>
        /// 生成json字符串
        /// </summary>
        [Test]
        public void Test14()
        {
            Person person = new Person
            {
                Id = "10232",
                FirstName = "Chuck",
                LastName = "Lu",
                Email = "chuck.lu@qq.com"
            };
            string str = JsonConvert.SerializeObject(person);
            Console.WriteLine(str);
        }
        
        /// <summary>
        /// 测试dynamic关键字的使用
        /// </summary>
        [Test]
        public void Test15()
        {
            string str = "{"Id":"10232","FirstName":"Chuck","LastName":"Lu","Email":"chuck.lu@qq.com"}";
            var temp = JsonConvert.DeserializeObject<dynamic>(str);
//这里都是硬编码调用的 Console.WriteLine($
@"{temp.Id} {temp.Id.GetType()}"); Console.WriteLine($@"{temp.FirstName} {temp.FirstName.GetType()}"); Console.WriteLine($@"{temp.LastName} {temp.LastName.GetType()}"); Console.WriteLine($@"{temp.Email} {temp.Email.GetType()}"); Console.WriteLine($@"{temp.Gender} {temp.Gender?.GetType()}"); //这里的Gender是null Console.WriteLine(); var person = JsonConvert.DeserializeObject<Person>(str); Console.WriteLine(person.GetType()); Console.WriteLine($@"{person.Id} {person.Id.GetType()}"); Console.WriteLine($@"{person.FirstName} {person.FirstName.GetType()}"); Console.WriteLine($@"{person.LastName} {person.LastName.GetType()}"); Console.WriteLine($@"{person.Email} {person.Email.GetType()}"); Console.WriteLine(); var people = JsonConvert.DeserializeObject<People>(str); Console.WriteLine(people.GetType()); }

json字符的转义,http://tool.what21.com/tool/javaStr.html

原文地址:https://www.cnblogs.com/chucklu/p/8472857.html