C 任意类型数据转JSON格式
发布时间:2021-06-05
发布时间:2021-06-05
C# 任意类型数据转JSON格式
///<summary>
/// List转成json
///</summary>
///<typeparam name="T"></typeparam>
///<param name="jsonName"></param>
///<param name="list"></param>
///<returns></returns>
publicstaticstringListToJson<T>(IList<T> list, stringjsonName) {
StringBuilderJson = newStringBuilder();
if (string.IsNullOrEmpty(jsonName))
jsonName = list[0].GetType().Name;
Json.Append("{\"" + jsonName + "\":[");
if (list.Count>0)
{
for (inti = 0; i<list.Count; i++)
{
T obj = Activator.CreateInstance<T>();
PropertyInfo[] pi = obj.GetType().GetProperties();
Json.Append("{");
for (int j = 0; j <pi.Length; j++)
{
Type type = pi[j].GetValue(list[i], null).GetType();
Json.Append("\"" + pi[j].Name.ToString() + "\":" +
StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
if (j <pi.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i<list.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]}");
returnJson.ToString();