dynamic关键字的使用

本文介绍了如何使用 Newtonsoft.Json 的 SerializeObject 和 DeserializeObject 方法来处理 JSON 数据,包括将 C# 对象序列化为 JSON 字符串及从 JSON 字符串中反序列化到指定类型的 C# 对象。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值