admin 管理员组

文章数量: 1184232


2024年4月13日发(作者:replace函数语法)

c#对象集合转Json

///

/// 普通集合转换Json

///

/// 集合对象

/// Json字符串

public static string ToArrayString(IEnumerable array)

{

string jsonString = "[";

foreach (object item in array)

{

jsonString = ToJson(ng()) + ",";

}

( - 1, );

return jsonString + "]";

}

///

/// 对象集合转换Json

///

/// 集合对象

/// Json字符串

public static string ToJson(IEnumerable array)

{

string jsonString = "[";

foreach (object item in array)

{

jsonString += ToJson(item) + ",";

}

( - 1, );

return jsonString + "]";

}

///

/// 对象转换为Json

///

/// 对象

/// Json字符串

public static string ToJson(object jsonObject)

{

string jsonString = "{";

PropertyInfo[] propertyInfo = e().GetProperties();

for (int i = 0; i < ; i++)

{

object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);

string value = ;

if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)

{

value = "'" + ng() + "'";

}

else if (objectValue is string)

{

value = "'" + ToJson(ng()) + "'";

}

else if (objectValue is IEnumerable)

{

value = ToJson((IEnumerable)objectValue);

}

else

{

value = ToJson(ng());

}

jsonString += """ + ToJson(propertyInfo[i].Name) + "":" + value + ",";

}

( - 1, );

return jsonString + "}";

}

///

/// List转换成Json

///

public static string ListToJson(IList list)

{

object obj = list[0];

return ListToJson(list, e().Name);

}

///

/// List转换成Json

///

public static string ListToJson(IList list, string jsonName)

{

StringBuilder Json = new StringBuilder();

if (OrEmpty(jsonName)) jsonName = list[0].GetType().Name;

("{"" + jsonName + "":[");

if ( > 0)

{

for (int i = 0; i < ; i++)

{

T obj = Instance();

PropertyInfo[] pi = e().GetProperties();

("{");

for (int j = 0; j < ; j++)

{

Type type = pi[j].GetValue(list[i], null).GetType();

(""" + pi[j].ng() + "":" + (pi[j].GetValue(list[i], null).ToString(), type));

if (j < - 1)

{

(",");

}

}

("}");

if (i < - 1)

{

(",");

}

}

}

("]}");

return ng();

}


本文标签: 集合 对象 语法 函数 作者