在使用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; } } ////// 生成json字符串 /// [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); } ////// 测试dynamic关键字的使用 /// [Test] public void Test15() { string str = "{\"Id\":\"10232\",\"FirstName\":\"Chuck\",\"LastName\":\"Lu\",\"Email\":\"chuck.lu@qq.com\"}"; var temp = JsonConvert.DeserializeObject(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 (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 (str); Console.WriteLine(people.GetType()); }
json字符的转义,