以下是代码:(我从数据库中读的数据,异常出现在红色的那行,异常名称为missingMethodException)using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Reflection;namespace ConsoleApplication1
{
public class ToJSon
{
public static string ListToJson<T>(IList<T> list, string jsonName){
StringBuilder Json = new StringBuilder(); if (string.IsNullOrEmpty(jsonName)) {
jsonName = list[0].GetType().Name;
}
Json.Append("{\"" + jsonName + "\":["); Console.WriteLine("********* "+list.Count+" ***********"); if (list.Count > 0){
for (int i = 0; i < list.Count; i++){
try
{
T obj = Activator.CreateInstance<T>();
PropertyInfo[] pi = obj.GetType().GetProperties();
Json.Append("{"); for (int j = 0; j < pi.Length; j++)
{
Type type = pi[j].GetValue(list[i], null).GetType();
Json.Append("\"" + pi[j].Name.ToString() + "\":" + String.Format(pi[j].GetValue(list[i], null).ToString(), type));
if (j < pi.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
}
catch (Exception e)
{
e.ToString();
}
if (i < list.Count - 1){
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Reflection;namespace ConsoleApplication1
{
public class ToJSon
{
public static string ListToJson<T>(IList<T> list, string jsonName){
StringBuilder Json = new StringBuilder(); if (string.IsNullOrEmpty(jsonName)) {
jsonName = list[0].GetType().Name;
}
Json.Append("{\"" + jsonName + "\":["); Console.WriteLine("********* "+list.Count+" ***********"); if (list.Count > 0){
for (int i = 0; i < list.Count; i++){
try
{
T obj = Activator.CreateInstance<T>();
PropertyInfo[] pi = obj.GetType().GetProperties();
Json.Append("{"); for (int j = 0; j < pi.Length; j++)
{
Type type = pi[j].GetValue(list[i], null).GetType();
Json.Append("\"" + pi[j].Name.ToString() + "\":" + String.Format(pi[j].GetValue(list[i], null).ToString(), type));
if (j < pi.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
}
catch (Exception e)
{
e.ToString();
}
if (i < list.Count - 1){
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
}
}
foreach(T obj in list)
{
........
}