将IList<T>泛型转换成Json
时间:2011-03-14 来源:Lyle Blog
private string SwitchToJson<T>(IList<T> li) where T : class { if (li.Count <= 0) return ""; Type tp = typeof(T); BindingFlags bf = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;//反射标识 PropertyInfo[] proInfo = tp.GetProperties(bf);//获取T的属性 StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; foreach (PropertyInfo info in proInfo)//遍历对象属性 { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName(info.Name); jsonWriter.WriteStartArray(); foreach (T item in li)//遍历每个对象 { object value = info.GetValue(item, null);//通过属性获取当前对象的属性值 jsonWriter.WriteValue(value.ToString()); } jsonWriter.WriteEndArray(); jsonWriter.WriteEndObject(); } } sw.Close(); return sb.ToString(); }其中的JsonWriter来自Newtonsoft.Json.Net20.dll
相关阅读 更多 +