【问题标题】:Get Length of array JSON.Net获取数组 JSON.Net 的长度
【发布时间】:2013-10-02 05:46:35
【问题描述】:

如何获取在 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 这样的东西太容易了:(..

【问题讨论】:

    标签: c# json json.net xamarin


    【解决方案1】:

    您可以将对象转换为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();
    

    但是,我个人并没有确认这会起作用

    【讨论】:

    • 你不需要投到JArray吗?
    • 我试过了,因为我在其他地方看到过。但不知何故我没有尝试 Count() ,似乎可行。我为自己的愚蠢感到非常抱歉:O
    • @Onno:你是说Count() 有效吗?如果是这样,我可以更新答案
    • 是的,我刚刚尝试过,它可以工作。 Count 在编译器中给我一个错误
    • 使用“.Count”,而不是“.Count()”
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      试试这个:

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

      【讨论】:

        【解决方案4】:

        我发现的最简单、最干净的方法:

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

        【讨论】:

          【解决方案5】:

          假设 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);
              }
          

          【讨论】:

            猜你喜欢
            • 2015-08-05
            • 2015-08-14
            • 1970-01-01
            • 2015-05-11
            • 2011-11-14
            • 1970-01-01
            • 1970-01-01
            • 2013-12-19
            • 2023-04-06
            相关资源
            最近更新 更多