解析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>……
}