C 任意类型数据转JSON格式(2)
发布时间:2021-06-05
发布时间:2021-06-05
///<summary>
/// List转成json
///</summary>
///<typeparam name="T"></typeparam>
///<param name="list"></param>
///<returns></returns>
publicstaticstringListToJson<T>(IList<T> list)
{
objectobj = list[0];
returnListToJson<T>(list, obj.GetType().Name);
}
///<summary>
/// 对象转换为Json字符串
///</summary>
///<param name="jsonObject">对象</param>
///<returns>Json字符串</returns>
publicstaticstringToJson(objectjsonObject)
{
stringjsonString = "{";
PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties(); for (inti = 0; i<propertyInfo.Length; i++)
{
objectobjectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
string value = string.Empty;
if (objectValueisDateTime || objectValueisGuid ||
objectValueisTimeSpan)
{
value = "'" + objectValue.ToString() + "'";
}
elseif (objectValueisstring)
{
value = "'" + ToJson(objectValue.ToString()) + "'";
}
elseif (objectValueisIEnumerable)
{
value = ToJson((IEnumerable)objectValue);
}
else
{
value = ToJson(objectValue.ToString());