C# 获取JSON.Net数组的长度
如何获得在C#中使用JSON.net获得的JSON数组的长度?发送SOAP调用后,我得到一个JSON字符串作为答案,我使用JSON.net解析它 我得到的json示例:C# 获取JSON.Net数组的长度,c#,json,json.net,xamarin,C#,Json,Json.net,Xamarin,如何获得在C#中使用JSON.net获得的JSON数组的长度?发送SOAP调用后,我得到一个JSON字符串作为答案,我使用JSON.net解析它 我得到的json示例: {"JSONObject": [ {"Id":"ThisIsMyId","Value":"ThisIsMyValue"}, {"Id":"ThisIsMyId2","Value":"ThisIsMyValue2"} ]} 我解析它并将其写入控制台: var test = JObject.Parse (json)
{"JSONObject": [
{"Id":"ThisIsMyId","Value":"ThisIsMyValue"},
{"Id":"ThisIsMyId2","Value":"ThisIsMyValue2"}
]}
我解析它并将其写入控制台:
var test = JObject.Parse (json);
Console.WriteLine ("Id: {0} Value: {1}", (string)test["JSONObject"][0]["Id"], (string)test["JSONObject"][0]["Value"]);
这就像一个咒语,只是我不知道JSONObject
的长度,但我需要在for循环中完成它。我只是不知道如何获得test[“JSONObject”]
但是类似于
test[“JSONObject”].Length的东西太简单了,我想:(…您可以将对象强制转换为JArray
,然后使用Count
属性,如下所示:
JArray items = (JArray)test["JSONObject"];
int length = items.Count;
然后可以按如下方式循环项目:
for (int i = 0; i < items.Count; i++)
{
var item = (JObject)items[i];
//do something with item
}
但是,我个人还没有确认这是否有效您可以使用下面的行获取.Net中JSON数组的长度(JArray
)
试试这个:
var test= ((Newtonsoft.Json.Linq.JArray)json).Count;
假设json数据在json文件中,这对我来说是有效的。
在这种情况下,.Length起作用,但没有可用的智能:
public ActionResult Index()
{
string jsonFilePath = "C:\\folder\\jsonLength.json";
var configFile = System.IO.File.ReadAllText(jsonFilePath);
JavaScriptSerializer jss = new JavaScriptSerializer();
var d = jss.Deserialize<dynamic>(configFile);
var jsonObject = d["JSONObject"];
int jsonObjectLength = jsonObject.Length;
return View(jsonObjectLength);
}
public ActionResult Index()
{
string jsonFilePath=“C:\\folder\\jsonLength.json”;
var configFile=System.IO.File.ReadAllText(jsonFilePath);
JavaScriptSerializer jss=新的JavaScriptSerializer();
var d=jss.Deserialize(configFile);
var jsonObject=d[“jsonObject”];
int jsonObjectLength=jsonObject.Length;
返回视图(jsonObjectLength);
}
我发现的最简单、最干净的方法:
int length = test["JSONObject"].Count;
你不需要投到JArray吗?我试过了,就像我在其他地方看到的那样。但是为什么我没有尝试Count(),什么似乎有效。我为我的愚蠢感到非常抱歉:O@Onno:你是说Count()
有效吗?如果可以,我可以更新答案是的,我刚刚尝试过,它有效。Count在编译器中给我一个错误,使用“.Count”,而不是“.Count()
public ActionResult Index()
{
string jsonFilePath = "C:\\folder\\jsonLength.json";
var configFile = System.IO.File.ReadAllText(jsonFilePath);
JavaScriptSerializer jss = new JavaScriptSerializer();
var d = jss.Deserialize<dynamic>(configFile);
var jsonObject = d["JSONObject"];
int jsonObjectLength = jsonObject.Length;
return View(jsonObjectLength);
}
int length = test["JSONObject"].Count;