Count JSON's Result

Emirates Angels 66 Reputation points
2020-12-29T16:29:54.557+00:00

Hi,

I have below json code and I want to know how can I get the count of the json's result, something like:

int total_found = data.Count;

Here is the code I am currently using:

var client = new HttpClient();

client.BaseAddress = new Uri("https://www.emiratesangels.org/api/generate_password_pin.php");

var content = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("email", TextEmail.Text.Trim()),
});

var response = await client.PostAsync("https://www.emiratesangels.org/api/generate_password_pin.php", content);

var result = await response.Content.ReadAsStringAsync();

PINData data = JsonSerializer.Deserialize<PINData>(result);

Thanks,
Jassim

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,479 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jaliya Udagedara 2,736 Reputation points MVP
    2020-12-29T18:55:52.84+00:00

    If the API you are calling returns an array of items (assuming an array of PINData), you need to deserialize the string content into List<PINData>

    List<PinData> data = JsonSerializer.Deserialize<List<PinData>>(result);
    // Now data.Count will give you the count of items
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,621 Reputation points
    2020-12-30T02:46:54.343+00:00

    Hi EmiratesAngels-2374,
    What is "TextEmail" and "PINData" in your code?
    Due to some uncertain objects in your code, I can't reproduce it.
    So have you got correct json string(result) by using Content.ReadAsStringAsync?
    If so, you can try the following code:

    JObject jObj = (JObject)JsonConvert.DeserializeObject(JsonString);  
    int count = jObj.Count;  
    

    Here are also some similar threads you can refer to.
    Count Number of Elements in JSON string with Json.NET in C#
    How to count number of JSON elements in an array in C#
    c# how to count the amount of json values
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments