zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    webstorm 2017 激活破解
    落在纸上的思考
    Mysql数据库备份脚本
    asp.net c# 打开新页面或页面跳转
    转正专业考试
    关于mysql-5.7.23-winx64.msi的安装
    win server 2012 R2 你需要先安装 对应于 KB2919355 的更新
    零碎
    按钮
    猪猪公寓——冲刺第一天
  • 原文地址:https://www.cnblogs.com/chucklu/p/8472857.html
Copyright © 2011-2022 走看看