Get Length of array JSON.Net

前端 未结 5 1379
失恋的感觉
失恋的感觉 2020-12-15 03:13

How can I get the length of a JSON Array I get using json.net in C#? After sending a SOAP call I get a JSON string as answer, I use json.net to parse it.

Example of

相关标签:
5条回答
  • 2020-12-15 03:18

    You can use below line to get the length of JSON Array in .Net (JArray) .

     int length = ((JArray)test["jsonObject"]).Count;
    
    0 讨论(0)
  • 2020-12-15 03:20

    Just try this:

    var test= ((Newtonsoft.Json.Linq.JArray)json).Count;
    
    0 讨论(0)
  • 2020-12-15 03:26

    You can cast the object to a JArray and then use the Count property, like so:

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

    You can then loop the items as follows:

    for (int i = 0; i < items.Count; i++)
    {
        var item = (JObject)items[i];
        //do something with item
    }
    

    According to Onno (OP), you can also use the following:

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

    However, I have not personally confirmed that this will work

    0 讨论(0)
  • 2020-12-15 03:27

    The easiest and cleanest way I found:

    int length = test["JSONObject"].Count;
    
    0 讨论(0)
  • 2020-12-15 03:39

    This worked for me supposing the json data is in a json file. In this case, .Length works but no intellisence is available:

        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);
        }
    
    0 讨论(0)
提交回复
热议问题