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
最新推荐文章于 2025-10-06 09:36:29 发布
本文介绍了一个使用C#实现的将对象列表转换为JSON字符串的方法。通过遍历对象属性并利用反射机制,该方法能够处理任意类型的对象,将其转换成标准的JSON格式。这对于数据交换和存储非常有用。
830

被折叠的 条评论
为什么被折叠?



