List转Json函数

    public string ObjectToJson<T>(string jsonName, IList<T> IL)
    {
        StringBuilder Json = new StringBuilder();
        Json.Append("{"" + jsonName + "":[");
        if (IL.Count > 0)
        {
            for (int i = 0; i < IL.Count; i++)
            {
                T obj = Activator.CreateInstance<T>();
                Type type = obj.GetType();
                PropertyInfo[] pis = type.GetProperties();
                 for (int j = 0; j < pis.Length; j++)
                {
                    Json.Append("" + pis[j].Name.ToString() + ":"" + pis[j].GetValue(IL[i], null) + """);
                    if (j < pis.Length - 1)
                    {
                        Json.Append(",");
                    }
                }
                 if (i < IL.Count - 1)
                {
                    Json.Append(",");
                }
            }
        }
        Json.Append("]}");

        return Json.ToString();
    }
原文地址:https://www.cnblogs.com/Shadow3627/p/3160238.html