在項目中總會用到son解析,好比RabbitMQ中使用json串解析,好比發過來的實體對象有50個字段,而實際只須要用到裏面的幾個字段,這時咱們建立實體時,只須要建立須要的幾個字段便可。json
測試實例,首先定義實體測試
/// <summary> /// 正常實體 /// </summary> public class Person { public Guid ID { get; set; } public string Name { get; set; } public int Age { get; set; } } /// <summary> /// 少一個實體參數 /// </summary> public class DeseriPersonFew { public Guid ID { get; set; } public string Name { get; set; } } /// <summary> /// 多一個實體參數 /// </summary> public class DeseriPersonMany { public Guid ID { get; set; } public string Name { get; set; } public int Age { get; set; } public int Sex { get; set; } }
實體解析測試,能夠建立解析實體,也能夠不建立實體對象,直接使用匿名類解析ui
static void Main(string[] args) { Console.WriteLine("Hello World!"); // NewMethod(); Person p = new Person(); p.ID = Guid.NewGuid(); p.Name = "zhangsan"; p.Age = 13; string personStr = JsonConvert.SerializeObject(p); //字段少於序列化實體 DeseriPersonFew personFew = JsonConvert.DeserializeObject<DeseriPersonFew>(personStr); if (personFew?.Name != null) Console.WriteLine("解析json時,字段少於序列化實體:" + personFew.Name); //解析時 大於原實體字段個數 DeseriPersonMany personMany = JsonConvert.DeserializeObject<DeseriPersonMany>(personStr); if (personMany?.Name != null) Console.WriteLine("解析json時,字段多於序列化實體:" + personMany.Name); //使用匿名類解析 var obj= JsonConvert.DeserializeAnonymousType(personStr,new { age=0,name=""}); Console.WriteLine("使用匿名類解析字段:" + obj?.name); Console.ReadLine(); }