///
/// List转成json
///
///
///
///
///
public static string ListToJson(IList list, string jsonName, int? p_rowCount)
{
StringBuilder Json = new StringBuilder();
if (string.IsNullOrEmpty(jsonName))
{
jsonName = "rows";
}
int? count = 0;
if (p_rowCount == null)
{
count = list.Count;
}
else
{
count = p_rowCount;
}
Json.Append("{\"total\":" + count + ",\"" + jsonName + "\":["); //\"totalCount\":" + count + ",
if (count > 0)
{
for (int i = 0; i < list.Count; i++)
{
T bj = Activator.CreateInstance();
PropertyInfo[] pi = obj.GetType().GetProperties();
Json.Append("{");
for (int j = 0; j < pi.Length; j++)
{
Type type = pi[j].PropertyType; //.GetValue(list[i], null) ?? string.Empty;
object o = pi[j].GetValue(list[i], null) ?? string.Empty;
Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(o.ToString(), type));
if (j < pi.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]}"); //]}
return Json.ToString();
}
///
///List转成json(不需要JSONname時使用該方法)
///
///
///
///
public static string ListToJson(List list,string jsonName, int? p_rowCount)
{
StringBuilder Json = new StringBuilder();
int? count = 0;
if (p_rowCount == null)
{
count = list.Count;
}
else
{
count = p_rowCount;
}
Json.Append("{\"total\":" + count + ",\"" + jsonName + "\":[");
// Json.Append("[");
if (count > 0)
{
for (int i = 0; i < list.Count; i++)
{
T bj = Activator.CreateInstance();
PropertyInfo[] pi = obj.GetType().GetProperties();
Json.Append("{");
for (int j = 0; j < pi.Length; j++)
{
Type type = pi[j].PropertyType; //.GetValue(list[i], null) ?? string.Empty;
object o = pi[j].GetValue(list[i], null) ?? string.Empty;
Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(o.ToString(), type));
if (j < pi.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
///
///List转成json(不需要JSONname時使用該方法)
///
///
///
///
public static string ListToJson(List list,int? p_rowCount)
{
StringBuilder Json = new StringBuilder();
int? count = 0;
if (p_rowCount == null)
{
count = list.Count;
}
else
{
count = p_rowCount;
}
Json.Append("[");
if (count > 0)
{
for (int i = 0; i < list.Count; i++)
{
T bj = Activator.CreateInstance();
PropertyInfo[] pi = obj.GetType().GetProperties();
Json.Append("{");
for (int j = 0; j < pi.Length; j++)
{
Type type = pi[j].PropertyType; //.GetValue(list[i], null) ?? string.Empty;
object o = pi[j].GetValue(list[i], null) ?? string.Empty;
Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(o.ToString(), type));
if (j < pi.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]");
return Json.ToString();
}
注:Json轉換(一二三)位於同一個Static類中
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/28699126/viewspace-759361/
,如需转载,请注明出处,否则将追究法律责任。