在项目中总会用到son解析,比如rabbitmq中使用json串解析,比如发过来的实体对象有50个字段,而实际只需要用到里面的几个字段,这时我们创建实体时,只需要创建需要的几个字段即可。

  测试实例,首先定义实体

    /// <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; }
    }

  实体解析测试,可以创建解析实体,也可以不创建实体对象,直接使用匿名类解析

 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();
        }