获取数组JSON.Net的长度

时间:2013-09-26 10:01:55

标签: 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);
Console.WriteLine ("Id: {0} Value: {1}", (string)test["JSONObject"][0]["Id"], (string)test["JSONObject"][0]["Value"]);

这就像一个咒语,只是我不知道JSONObject的长度,但我需要在for循环中进行。我只是不知道如何获得test["JSONObject"]

的长度

但是像test["JSONObject"].Length这样的东西我觉得太容易了:(..

5 个答案:

答案 0 :(得分:59)

您可以将对象强制转换为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
}

根据Onno(OP),您还可以使用以下内容:

int length = test["JSONObject"].Count();

但是,我没有亲自确认这会起作用

答案 1 :(得分:1)

这对我有用,假设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);
    }

答案 2 :(得分:0)

您可以使用以下行在.Net(JArray)中获取JSON数组的长度。

 int length = ((JArray)test["jsonObject"]).Count;

答案 3 :(得分:0)

只需尝试一下:

var test= ((Newtonsoft.Json.Linq.JArray)json).Count;

答案 4 :(得分:0)

我发现的最简单,最干净的方法

int length = test["JSONObject"].Count;