Extracting information from multiple JSON arrays in C#

Searching for statistics in this Json Code is my goal:

{
    "summonerId": 32033681,
    "modifyDate": 1403658807000,
    "champions": [{
        "id": 40,
        "stats": {
            "totalSessionsPlayed": 1,
            "totalSessionsLost": 0,
            "totalSessionsWon": 1,
            "totalChampionKills": 1,
            "totalDamageDealt": 27006,
            "totalDamageTaken": 9924,
            "mostChampionKillsPerSession": 1,
            "totalMinionKills": 17,
            "totalDoubleKills": 0,
            "totalTripleKills": 0,
            "totalQuadraKills": 0,
            "totalPentaKills": 0,
            "totalUnrealKills": 0,
            "totalDeathsPerSession": 2,
            "totalGoldEarned": 8383,
            "mostSpellsCast": 0,
            "totalTurretsKilled": 2,
            "totalPhysicalDamageDealt": 8957,
            "totalMagicDamageDealt": 18049,
            "totalFirstBlood": 0,
            "totalAssists": 13,
            "maxChampionsKilled": 1,
            "maxNumDeaths": 2
        }
    },
    {
        "id": 36,
        "stats": {
            "totalSessionsPlayed": 1,
            "totalSessionsLost": 1,
            "totalSessionsWon": 0,
            "totalChampionKills": 0,
            "totalDamageDealt": 14267,
            "totalDamageTaken": 7649,
            "mostChampionKillsPerSession": 0,
            "totalMinionKills": 33,
            "totalDoubleKills": 0,
            "totalTripleKills": 0,
            "totalQuadraKills": 0,
            "totalPentaKills": 0,
            "totalUnrealKills": 0,
            "totalDeathsPerSession": 5,
            "totalGoldEarned": 3258,
            "mostSpellsCast": 0,
            "totalTurretsKilled": 0,
            "totalPhysicalDamageDealt": 4992,
            "totalMagicDamageDealt": 9165,
            "totalFirstBlood": 0,
            "totalAssists": 0,
            "maxChampionsKilled": 0,
            "maxNumDeaths": 5
        }
    }]
}

In this particular example, my objective is to find the total number of sessions won for Champion ID 36. However, I am unable to access this specific data as I typically would with other JSON files because it doesn't allow me to specify the champion's ID:

string jsonInput = new WebClient().DownloadString(@usableurl); // Retrieves the JSON from the API
string usableJson = @"JObject.Parse(jsonInput)"; // Converts the JSON into a usable format
var usableJson["champions"]["stats"]["totalSessionWon"];

Is there any way for me to choose a specific statistic based on its preceding ID?

I'm relatively new to working with both JSON and C#, so your assistance is greatly appreciated!

Answer №1

If you're unfamiliar with the library Newtonsoft.Json;, here's a step-by-step guide on how to install Newtonsoft. Once installation is complete, I'll let you in on a little secret: XML and JSON are formats that utilize human-readable text to transmit data objects which consist of attribute–value pairs. Retrieving data from these string formats is as easy as working with a database.

In order to efficiently retrieve data from a JSON string, we first need to create an object representation that reflects its hierarchy. Take a look at what your data or JSON string looks like. At the topmost level, you'll find attributes such as summonerId, modifyDate, and champions. Within champions, there could be an indefinite number of champion details, so we've created a list called champions.

Moving down one level in the hierarchy, you'll see the champion ID and their stats. So, we need to create another class to represent the stats of each champion. Your classes will therefore look something like this:

public class Rootobject
{
    public int summonerId { get; set; }
    public long modifyDate { get; set; }
    public List<Champion> champions { get; set; }
}

public class Champion
{
    public int id { get; set; }
    public Stats stats { get; set; }
}

public class Stats
{
    public int totalSessionsPlayed { get; set; }
    public int totalSessionsLost { get; set; }
    public int totalSessionsWon { get; set; }
    public int totalChampionKills { get; set; }
    public int totalDamageDealt { get; set; }
    public int totalDamageTaken { get; set; }
    public int mostChampionKillsPerSession { get; set; }
    public int totalMinionKills { get; set; }
    public int totalDoubleKills { get; set; }
    public int totalTripleKills { get; set; }
    public int totalQuadraKills { get; set; }
    public int totalPentaKills { get; set; }
    public int totalUnrealKills { get; set; }
    public int totalDeathsPerSession { get; set; }
    public int totalGoldEarned { get; set; }
    public int mostSpellsCast { get; set; }
    public int totalTurretsKilled { get; set; }
    public int totalPhysicalDamageDealt { get; set; }
    public int totalMagicDamageDealt { get; set; }
    public int totalFirstBlood { get; set; }
    public int totalAssists { get; set; }
    public int maxChampionsKilled { get; set; }
    public int maxNumDeaths { get; set; }
}

Now that we've established the structure, we need to Deserialize the string into an object of our created type, Rootobject. This will convert the plain JSON string into individual objects. From there, fetching details is as effortless as eating a piece of cake.

using Newtonsoft.Json;

Rootobject rt = JsonConvert.DeserializeObject<Rootobject>(jsonstr);
if(rt.champions[1].id == 36)
{
    Console.WriteLine(rt.champions[1].stats.totalSessionsWon);
}

Answer №2

While assisting the author of the question in utilizing the JObject library to query their JSON object, it dawned upon me to provide a solution using the same approach.

The essence of querying JSON with JObject lies in its integration with Linq, which serves as a specialized query language for extracting data from various sources. However, I acknowledge that Linq can be quite challenging for new C# programmers to comprehend. In light of this, Mohit Shrivastrava's answer presents a simpler alternative for newcomers to grasp.

// Parses the API's JSON into an accessible format
JObject usableJson = JObject.Parse(json); 

// Retrieves champion objects
JToken champions = usableJson["champions"];

// Finds the desired champion object using Linq's FirstOrDefault method.
// This method returns the first matching object based on the provided query,
// otherwise, null if no match is found.
JToken champion = champions.FirstOrDefault(c=> (int)c["id"] == 36);

if (champion != null)
{
    // Retrieves the stats object
    JToken stats = champion["stats"];

    // Extracts the value of totalSessionsWon field from the object.
    int totalSessionsWon = (int) stats["totalSessionsWon"];
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Node to parse XLSX files and generate JSON data

Hello, I am currently utilizing the js-xlsx package which can be found at this link. My inquiry is how to successfully parse an xlsx file with merges and convert it into JSON format. You can view what the excel sheet looks like here. Ultimately, the JSON o ...

Convert C# webapi date formats to Java using Gson

I have a C# webapi project that returns instances of an object called foo. The foo object in C# has two DateTime properties. I've set up my webapi to always display seven decimal places after the time. This is how it looks when serialized into JSON: ...

The error `Uncaught TypeError: array_unique(): Argument #1 ($array) must be of type array, string given` suggests that the

I am encountering an issue while attempting to obtain unique values in the option menu within a select element by using the array_unique() function. However, I keep receiving the following error message: Fatal error: Uncaught TypeError: array_unique(): A ...

extract several fields from a json object

In need of converting JSON data into a tabular format for later transformation to parquet. Schema root |-- : string (nullable = true) sample data +----------------------------------------------+ +----------------------------------------------+ |{"d ...

Using opening and closing curly braces within a PHP foreach loop

I am facing an issue with formatting an array in PHP. The array structure is as follows: Array ( [0] => Array ( [team1_score] => 10 [team2_score] => 5 [round_number] => 1 [teamtitle1] ...

Transforming the MySQL result array into JSON format

I am looking to transform the array result retrieved from my database query into JSON format using PHP. Below is the code snippet I am currently working with: $row = mysql_fetch_array($result) My goal is to convert the variable $row into JSON format and t ...

Exploring the Depths of Multidimensional JSON Arrays in PHP

I am currently working on developing a web-based file manager that allows me to organize, view, create, edit, and delete folders and files. In order to store information about these folders, files, and subfolders, I am in need of an appropriate data struct ...

Organize Selenium Elements in C# without Using Tables

I'm faced with a challenge on a page that contains 3 columns and the ability to sort by date using a button. I've been struggling to find a solution for this, but so far, no luck. Below is an example of a single record, and there could potentiall ...

Leveraging the get_account_funds function within the betfair.py library

I have been attempting to utilize the get_account_funds function in the betfair.py package found at https://github.com/jmcarp/betfair.py. The example code provided in the readme file demonstrates the list_event_types function working correctly, indicating ...

Exploring the Interplay of JSON Objects in SQL Server and C#

After executing the following SQL Server query, I successfully created a JSON object: SELECT Attribute 1, Attribute 2, Attribute 3,... AS Identifier FROM Table_1 tbl1_obj INNER JOIN Table_2 tbl2_obj ON tbl2_obj.Id = tbl1_obj.Id FOR JSON AU ...

Combining a JSON file and a CSV file into a pandas dataframe for analysis

I have a JSON file with geographic data that includes information on population counts for different areas represented by WK_CODE. { "type" : "FeatureCollection", "name" : "NBG_DATA.CBSWBI", "feature ...

Assessing the string to define the structure of the object

Currently, I am attempting to convert a list of strings into a literal object in Javascript. I initially tried using eval, but unfortunately it did not work for me - or perhaps I implemented it incorrectly. Here is my example list: var listOfTempData = [ ...

Using JSON to pass a function with parameters

I have a small issue that I'm struggling to solve. My dilemma lies in sending a JSON with a function, along with parameters. Typically, it's easy to send a function in JSON like this: var jsonVariable = { var1 : 'value1', var2 : &apos ...

Sending user input from search component to main App.js in React

I'm currently working on an app that searches a Movies database API. I have a main fetch function in App.js, and in tutorials, people are using a search bar within this main APP component. I'm wondering if it would be better to create a separate ...

Adding information to an HTML table using JQuery

Is there a way to incorporate JSON data into an HTML table? The JSON data follows this format: https://i.stack.imgur.com/lzdZg.png This is the desired HTML table structure: <table class="table table-bordered table-hover "> ...

What is causing the difficulty in accessing the 'query' feature within the API, and why is the question bank failing to display?

Just wanted to mention that I am still learning about class based components, setState, and other concepts in async JS like axios. Below is a very basic example of what I can currently do. This is App.js: import Questions from './components/Ques ...

What is the best way to eliminate the additional square bracket from a JSON file containing multiple arrays?

Seeking JSON data from an array, I encountered an issue with an extra square bracket appearing in the output. After attempting $episode[0] = $podcast->getPodcastByCategoryId($id);, only partial data was retrieved, corresponding to the first iteration. ...

Navigating and extracting nested JSON properties using JavaScript (React)

I am currently working with a nested JSON file that is being fetched through an API. The structure of the JSON file looks something like this: { "trees":{ "name":"a", "age":"9", "h ...

Tips for building a versatile fetch function that can be reused for various JSON formats within a React application

Using the fetch method in various components: fetch(url) .then(result => { if (!result.ok) { throw new Error("HTTP error " + result.status) } return result.json() }) .then(result => { ...

Flexigrid, link to fill the grid

Recently, I created an application that retrieves data from a MySQL database (datatype:json and url:post.php) to populate the grid successfully. However, I am now exploring different methods to retrieve the data rather than just using a PHP file. One idea ...