如何将List集合转Json

public string ListToJSON<T>(List<T> objlist)
{
     string result = "";

     result += "[";
     bool firstline = true;//这里是在处理第一行的前面不加","号
     foreach (object oo in objlist)
     {
         if (!firstline)
         {
             result = result + "," + OneObjectToJSON(oo);
         }
         else
         {
             result = result + OneObjectToJSON(oo) + "";
             firstline = false;
         }
     }
     return result + "]";
}
private string OneObjectToJSON(object o)
{
    string result = "{";
    List<string> ls_propertys = new List<string>();
    ls_propertys = GetObjectProperty(o);
    foreach (string str_property in ls_propertys)
    {
        if (result.Equals("{"))
        {
            result = result + str_property;
        }
        else
        {
            result = result + "," + str_property + "";
        }
    }
    return result + "}";
}
private List<string> GetObjectProperty(object o)
{
    List<string> propertyslist = new List<string>();
    PropertyInfo[] propertys = o.GetType().GetProperties();
    foreach (PropertyInfo p in propertys)
    {
        propertyslist.Add("\"" + p.Name.ToString() + "\":\"" + p.GetValue(o, null) + "\"");
    }
    return propertyslist;
}

你可能感兴趣的:(List转Json)