不知道类型的 Json 列表计数
Count of Json List without knowing the Type
使用 GET API 方法,我需要获取 table 和 Entity Framework 的所有记录的计数。该方法接收一个 table 名称,我通过这个名称获取程序集并获取所有记录。但结果是 JSON,我还没有找到如何计算这个数。
这是我的代码:
try
{
Type t = Type.GetType("Iwg.Transverse.Business." + tableName + "Manager, Iwg.Transverse.Business, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
MethodInfo method = t.GetMethod("GetAll", Type.EmptyTypes);
var executionMethod = method.Invoke(Activator.CreateInstance(t), null);
JsonResult<object> json = this.Json(executionMethod);
//This line does not work.
//return this.Json(json .Count + 1);
}
catch (Exception e)
{
return this.Json("Error getting the table " + tableName + "\nError " + e.Message);
}
如果没有可用的方法,我想你可以单独做一个简单的 foreach 循环来做到这一点。
int count=0;
foreach (var package in json)
{
count = count++;
}
return this.Json(count.ToString());
来自 here 的已编辑回复:
dynamic response = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<dynamic>(json);
return (response.Length);
从你的问题中不完全清楚 GetAll
returns 是 JSON 数组,还是 returns 某种 IEnumerable
(或其他东西) else) 然后将其转换为 JSON。 (问题的文字似乎暗示了前者,但代码似乎暗示了后者。)
如果 GetAll
总是 returns 表示项目数组的 JSON 字符串,那么您可以执行以下操作来获取计数:
int count = Newtonsoft.Json.Linq.JArray.Parse((string)executionMethod).Count;
如果 GetAll
方法总是 returns 某种 IEnumerable
而不是 JSON,您可以执行以下操作来获取计数:
int count = ((IEnumerable)executionMethod).Cast<object>().Count();
(请注意,您的代码顶部需要 using System.Linq;
才能正常工作。)
如果 GetAll
returns 其他东西,例如 JSON 对象 (不是数组,但可能 包含 数组)或其他类型的对象,那么我们需要了解有关它是什么的更多详细信息。
使用 GET API 方法,我需要获取 table 和 Entity Framework 的所有记录的计数。该方法接收一个 table 名称,我通过这个名称获取程序集并获取所有记录。但结果是 JSON,我还没有找到如何计算这个数。
这是我的代码:
try
{
Type t = Type.GetType("Iwg.Transverse.Business." + tableName + "Manager, Iwg.Transverse.Business, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
MethodInfo method = t.GetMethod("GetAll", Type.EmptyTypes);
var executionMethod = method.Invoke(Activator.CreateInstance(t), null);
JsonResult<object> json = this.Json(executionMethod);
//This line does not work.
//return this.Json(json .Count + 1);
}
catch (Exception e)
{
return this.Json("Error getting the table " + tableName + "\nError " + e.Message);
}
如果没有可用的方法,我想你可以单独做一个简单的 foreach 循环来做到这一点。
int count=0;
foreach (var package in json)
{
count = count++;
}
return this.Json(count.ToString());
来自 here 的已编辑回复:
dynamic response = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<dynamic>(json);
return (response.Length);
从你的问题中不完全清楚 GetAll
returns 是 JSON 数组,还是 returns 某种 IEnumerable
(或其他东西) else) 然后将其转换为 JSON。 (问题的文字似乎暗示了前者,但代码似乎暗示了后者。)
如果 GetAll
总是 returns 表示项目数组的 JSON 字符串,那么您可以执行以下操作来获取计数:
int count = Newtonsoft.Json.Linq.JArray.Parse((string)executionMethod).Count;
如果 GetAll
方法总是 returns 某种 IEnumerable
而不是 JSON,您可以执行以下操作来获取计数:
int count = ((IEnumerable)executionMethod).Cast<object>().Count();
(请注意,您的代码顶部需要 using System.Linq;
才能正常工作。)
如果 GetAll
returns 其他东西,例如 JSON 对象 (不是数组,但可能 包含 数组)或其他类型的对象,那么我们需要了解有关它是什么的更多详细信息。