0

The point of the program is to find the total number of films a character has been a part of.

I'm trying to access a Newtonsoft.Json.Linq.JArray type object to count the length of a multidimensional array.

Json array:

{
    "count": 1, 
    "next": null, 
    "previous": null, 
    "results": [
        {
            "name": "Luke Skywalker", 
            "height": "172", 
            "mass": "77", 
            "hair_color": "blond", 
            "skin_color": "fair", 
            "eye_color": "blue", 
            "birth_year": "19BBY", 
            "gender": "male", 
            "homeworld": "descriptiontext", 
            "films": [
                "linkapifilms1", 
                "linkapifilms2", 
                "linkapifilms3", 
                "linkapifilms6", 
                "linkapifilms7"
            ], 
            "species": [], 
            "vehicles": [
                "linapivehicles14", 
                "linapivehicles30"
            ], 
            "starships": [
                "linapistarships12", 
                "linapistarships22"
            ], 
            "created": "2014-12-09T13:50:51.644000Z", 
            "edited": "2014-12-20T21:17:56.891000Z", 
            "url": "linkapipeople1"
        }
    ]
}

I'm trying to access "films": to count the length of the array and store/display it on an int variable.

My Code:

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class Solution
{
    static void Main()
    {

        Console.WriteLine("Number of films: " + Run("Luke Skywalker"));
        Console.ReadKey();
    }

    static public int Run(string character)
    {

        int numberOfFilms = 0;
        Task<string> result = GetResponseString(character);
        var jsonResult = result.Result;

        dynamic dynamicResultObject = JsonConvert.DeserializeObject(jsonResult);

        JArray x = dynamicResultObject.results;
        //Find length of "films" code insert//
        Console.WriteLine(character);
        return numberOfFilms;
    }
    static public async Task<string> GetResponseString(string character)
    {

        var httpClient = new HttpClient();
        var response = await httpClient.GetAsync("linktoapi/api/people/?search=" + character);
        var contents = await response.Content.ReadAsStringAsync();

        return contents;
    }
}

I can access the first line of array with dynamicResultObject.results;

So the question is how do I access films, which is inside results and find the length?

Edit: I understand that this may not be the best way to go about writing this program however, is it not possible to just access the child array of the main array with the current code?

3
  • 1
    var jsonResult = result.Result; this is a bad idea. You should be awaiting GetResponseString Commented Oct 3, 2019 at 13:01
  • Possible duplicate of How can I parse JSON with C#? Commented Oct 3, 2019 at 13:02
  • 1
    I'd like to suggest you follow the procedure from this answer which you will give you strong typed objects that are very easy to work with. Commented Oct 3, 2019 at 13:03

1 Answer 1

4

First of all, I would advise against using dynamic as it will just cause you headaches. If you're going to work with JObjects and JArrays anyway you're better off just using those types directly. The compiler will be able to detect errors earlier and you will get the Intellisense help in Visual Studio. So, parse your JSON like this:

JObject rootObject = JObject.Parse(jsonResult);

From that you can get your results array. (You were calling this array x in your code, but I think resultsArray is a more descriptive variable name):

JArray resultsArray = (JArray)rootObject["results"];

Like any array, if you want to get at a particular element you need to use its index. We can get the first element of the array (which is the object containing Luke Skywalker's data) like this:

JObject characterObject = (JObject)resultsArray[0];

From there, you can get the films property, which is also a JArray:

JArray filmsArray = (JArray)characterObject["films"];

To get the length of a JArray you use the Count property:

numberOfFilms = filmsArray.Count;

Fiddle: https://dotnetfiddle.net/iFAWB4

Now that you know how to drill down through the objects and arrays step-by-step, I'll show you a little shortcut, the SelectToken() method. This method allows you to specify a "path" to get a particular JToken (JObject and JArray are both types of JTokens). So, after parsing your JSON, you could get the films array directly like this:

JArray filmsArray = (JArray)rootObject.SelectToken("results[0].films");

and then get its count just like before.

Fiddle: https://dotnetfiddle.net/zOdSFs

Sign up to request clarification or add additional context in comments.

2 Comments

Wow thanks! Seriously appreciate the step by step breakdown of your answer, reliever of headaches.
Glad I could help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.