c# 利用反射动态给实体类对象赋值

解析json,在网上找了一些好的方法,做一下整理分享一下
</pre><pre name="code" class="csharp">public List<Metadata> GetMetadata(string json)
        {
            JObject jo = (JObject)JsonConvert.DeserializeObject(json);
            List<Metadata> solrResult = new List<Metadata>();
            if (jo != null)
            {
                JToken jt = null;
                jo.TryGetValue("docs", out jt);
                if (jt != null)
                {
                    foreach (JObject item in jt)
                    {
                        Type type = typeof(Metadata);//获取类型信息
                        Metadata metadata = new Metadata();
                        PropertyInfo[] properties = type.GetProperties();//获取指定对象的所有公共属性
                        foreach (PropertyInfo property in properties)
                        {
                            JToken jTemp = null;
                            string proName = property.Name;
                            Attribute[] displayNames = Attribute.GetCustomAttributes(property, false);
                            if (displayNames == null || displayNames.Length <1)
                            {
                                continue;
                            }
                            string name = ((DisplayNameAttribute)displayNames[0]).DisplayName;

                            if (item.TryGetValue(name, out jTemp))
                            {
                                if (property.PropertyType == typeof(ICollection<string>))
                                {
                                    property.SetValue(metadata, jTemp.ToObject<ICollection<string>>(), null);
                                }
                                else
                                {
                                    property.SetValue(metadata, jTemp.ToString(), null);//给对象赋值
                                }
                            }
                        }
                        solrResult.Add(metadata);
                    }
                }
            }
            return solrResult;
        }
</pre><pre name="code" class="csharp">class Metadata
    {
        /// <summary> 
        ///题名 
        /// </summary> 
        [DisplayName("title")]
        public string Title { get; set; }
        /// <summary> 
        ///作者 
        /// </summary> 
        [DisplayName("creator")]
        public string Creator { get; set; }
        /// <summary> 
        ///资源类型 
        /// </summary> 
        [DisplayName("type")]
        public ICollection<String> Type { get; set; }
<span style="white-space:pre">		</span>
<span style="white-space:pre">	</span>……
     }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值