怎么将泛型返回值转换成json
发布网友
发布时间:2022-04-27 07:50
我来回答
共1个回答
热心网友
时间:2022-06-28 18:15
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();
}