Search code examples
c#jsonhttpclientdatacontractjsonserializerhttpresponsemessage

C# how can I get a count of Json with several levels


I have a json like this one that comes from an api. I´m using oauth2 so i got the token, then I request the data. I want to count the name inside resources, to know how many are.

{
  "startDate": "2019-06-23T16:07:21.205Z",
  "endDate": "2019-07-24T16:07:21.205Z",
  "status": "Complete",
  "usages": [
    {
      "name": "PureCloud Edge Virtual Usage",
      "resources": [
        {
          "name": "Edge01-VM-GNS-DemoSite01 (1f279086-a6be-4a21-ab7a-2bb1ae703fa0)",
          "date": "2019-07-24T09:00:28.034Z"
        },
        {
          "name": "329ad5ae-e3a3-4371-9684-13dcb6542e11",
          "date": "2019-07-24T09:00:28.034Z"
        },        
        {
          "name": "e5796741-bd63-4b8e-9837-4afb95bb0c09",
          "date": "2019-07-24T09:00:28.034Z"
        }
      ]
    },
    {
      "name": "PureCloud for SmartVideo Add-On Concurrent",
      "resources": [
        {
          "name": "[email protected]",
          "date": "2019-06-25T04:54:17.662Z"
        },
        {
          "name": "[email protected]",
          "date": "2019-06-25T04:54:17.662Z"
        },        
        {
          "name": "[email protected]",
          "date": "2019-07-15T15:06:09.203Z"
        }
      ]
    },
    {
      "name": "PureCloud 3 Concurrent User Usage",
      "resources": [
        {
          "name": "[email protected]",
          "date": "2019-06-25T04:54:17.662Z"
        },
        {
          "name": "[email protected]",
          "date": "2019-06-25T04:54:17.662Z"
        },       
        {
          "name": "[email protected]",
          "date": "2019-07-15T15:06:09.203Z"
        }
      ]
    },
    {
      "name": "PureCloud Skype for Business WebSDK",
      "resources": [
        {
          "name": "[email protected]",
          "date": "2019-06-25T04:54:17.662Z"
        },
        {
          "name": "[email protected]",
          "date": "2019-06-25T04:54:17.662Z"
        },      
        {
          "name": "[email protected]",
          "date": "2019-07-15T15:06:09.203Z"
        }
      ]
    }
  ],
  "selfUri": "/api/v2/billing/reports/billableusage"
}

This are the classes that i use.

   public class Resources
    {
        public string name { get; set; }
        public DateTime date { get; set; }
    }

    public class Usages
    {
        public string name { get; set; }
        public IList<Resources> resources { get; set; }
    }

    public class Example
    {
        public DateTime startDate { get; set; }
        public DateTime endDate { get; set; }
        public string status { get; set; }
        public IList<Usages> usages { get; set; }
        public string selfUri { get; set; }
    }

This is the function that I use, it receives the url and the token and it gets the data:

static async Task<int> GetNamesCount(string theUrl, string theToken)        
        {
            using (var client = new HttpClient())
            {
                Records records = new Records();                
                client.BaseAddress = new Uri(theUrl);               
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", theToken);

                try
                {

                    HttpResponseMessage response = await client.GetAsync(theUrl);
                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();                    
                    records = (Records)new DataContractJsonSerializer(typeof(Records)).ReadObject(response.Content.ReadAsStreamAsync().Result);

I´ve tried, but I can only count the first two levels. I´ve searched but I can´t use [1] or records.usages["resources"]. What can I do? Thanks in advance.


Solution

  • You could use SelectMany to fetch all resources name inside usages list, and use Count method to calculate the count of names insides resources :

    int countNames = records.usages.SelectMany(x => x.resources.Select(y => y.name)).Count();
    

    Or Use Sum with count, like :

    int countNames = records.usages.Sum(x => x.resources.Count(y => y.name != null));
    

    If you want just the count of names inside Usages, you could use :

    int countUsagesNames = records.usages.Count;
    // or
    int countUsagesNames = records.usages.Count(x => x.name != null);
    

    I hope you find this helpful.