What is the best way to transform JSON data into a dictionary in C# and access it using a string key?

Currently, I am working on creating a dictionary for indexing JSON values with strings. To achieve this, I am utilizing Newtonsoft to deserialize the JSON string. Here is an example of my JSON data:

 {
    "financialPositions": [
      {
        "fieldName": "Assets",
        "periodEndToDateValue": 0.0,
        "pastYearEndToDateValue": 0.0,
        "description": "\u062f\u0627\u0631\u0627\u06cc\u06cc\u200c\u200c\u0647\u0627",
        "percentChanges": 0.0,
        "rowClass": "GroupHeader"
      },
      {
        "rowClass": "ComputationalRow",
        "fieldName": "ListedCapital",
        "description": "\u0633\u0631\u0645\u0627\u06cc\u0647",
        "percentChanges": 0.0,
        "currentPeriodEndToDateValue": 1.0,
        "pastSimillarEndToDateValue": 1.0,
        "pastYearEndToDateValue": 1.0
      }
    ]
  }

The classes I have used are as follows:

public class RootObject
{
    public FinancialPositions[] financialPositions{ get; set; }
}

public class FinancialPositions
{
    public string fieldName { get; set; }
    public double periodEndToDateValue { get; set; }
    public double pastYearEndToDateValue { get; set; }
    public string description { get; set; }
    public float percentChanges { get; set; }
    public string rowClass { get; set; }
}

To deserialize the JSON string, I use the following code snippet:

RootObject oRootObject = new RootObject();
oRootObject  = JsonConvert.DeserializeObject<RootObject>(jsonstring);

If you want to make changes to access specific parts of the deserialized object, you can do so by addressing them like below:

oRootObject.financialPositions["Assets"]

Answer №1

To create a custom indexer using [], you can define it for your object.

public class RootObject
{
    public FinancialPositions[] financialPositions{ get; set; }

    public object this[string name]
    {
          get { return financialPositions.FirstOrDefault(f => f.fieldName  == name); }
          set { }
    }
}

After defining the indexer, simply call

oRootObject["Assets"] to retrieve the specific object

{
        "fieldName": "Assets",
        "periodEndToDateValue": 0.0,
        "pastYearEndToDateValue": 0.0,
        "description": "\u062f\u0627\u0631\u0627\u06cc\u06cc\u200c\u200c\u0647\u0627",
        "percentChanges": 0.0,
        "rowClass": "GroupHeader"
 }

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

In the realm of asp.net mvc, JSON remains a mysterious and undefined

When working with ASP.NET MVC 3, I have encountered an issue regarding JSON in my AJAX calls. The application runs smoothly on my development machine when using Visual Studio. However, after publishing the same application and trying to access it through a ...

Changing a 2D List into a 2D String Array in C#

Currently, I am dealing with CSV files, however, all the guides I have come across utilize 2D Lists. private void loadCSV() { List<string[]> values = new List<string[]>(); var reader = new StreamReader(File.OpenRead(*my fi ...

Adding information to a form with jQuery

To obtain data in this particular format, I use the following method: form = $(this).parents('form'); Afterwards, to submit the data using jQuery form, I utilize the code snippet below: form.ajaxSubmit() Prior to submitting, I need to append ...

Obtaining an element with jQuery results in an undefined value

Below is the snippet of code where I retrieve my input element using jQuery: var txt = $(tableRow).find('input:text'); if (txt.value == null) { //TO DO code } and this is how I achieve it with pure JavaScript var txt = document.getElementByI ...

Scope isolation prevents variables from being accessed in higher levels of the scope chain

In my search for answers, I came across some similar questions on SO: Isolate scope variable is undefined unable to access rootscope var in directive scope However, my question presents a unique scenario. I am facing an issue with a directive that has a ...

The JSON.parse function encountered an unexpected end of data during the JSON call

I've been searching various online forums for a solution to my issue, but I'm unable to figure out why this problem persists. My setup involves a web server that sends back a JSON object: http://213.125.101.19/api.php?function=test Subsequentl ...

I am encountering an issue with identifying a directory in Node.js

This is my HTML code <div id="done_work_1" class="logo-slide-track"> </div> <script>$.ajax({ url: "/static/home/done/", success: function (data) { $(data).find("a").attr("href&q ...

strange issue encountered while utilizing JavaScript's async/await syntax

Recently, I encountered an issue while trying to retrieve a random user from the randomuser API using code in my Vue frontend. // Here is the structure of the API response { info: { // details omitted }, results: [ {//random user data} ] } // This snippet ...

Exploring nested JSON information through jQuery's AJAX call

I am encountering an issue with accessing JSON data using a jQuery AJAX request in JavaScript. I keep receiving a 'Cannot read property [0] of undefined' error in the console of Google Chrome. Despite trying different approaches, such as referrin ...

Discovering the method for keeping track of file changes and executing find-replace operations without registering it as an event within the monitored file

I am confused about why the output displays two lines when typing 'fizbuzz' into the test.txt file. I understand that it is performing a find and replace operation, but how can I avoid it being triggered by the watch function? const watch = requ ...

converting HTML data to JSON format

Here is a basic example to consider: import pandas as pd import numpy as np import requests from bs4 import BeautifulSoup df = pd.DataFrame({'link' : ['https://en.wikipedia.org/wiki/World%27s_funniest_joke', ...

Tips for effectively utilizing hyperlinks in Medium Editor

Recently, I've been exploring the amazing capabilities of a tool called Medium Editor. However, I've come across an issue where I can't seem to get links to function properly. To illustrate the problem simply, here is some HTML/JS code that ...

What can Cordova and express js bring to the table together?

I'm feeling pretty lost when it comes to displaying express views in a Cordova app client. It seems like the app would have to send a GET request and then the express application would render the view. But I'm unsure about how to actually make t ...

Adjust the appearance of matSelect when the selection menu is activated

What is the best way to adjust mat-select properties when its options are open? <mat-select class="selector"> <mat-option><mat-option> </mat-select> .selector:focus { color: green; } I attempted using focus, but ...

Creating static HTML pages with client-side caching and parameter passing

I am in the process of developing a robust mobile application using jQuery Mobile and KnockoutJS. Initially, I utilized a Single Page Application structure with heavy reliance on Knockout and ajax calls to load dynamic content and data. While this approach ...

Point light in Three.js is not functional when used with oversized meshes

Experiencing an issue with using Three.js point light in my project. Here's what I have: var color = 0xffffff; var intensity = 0.5; var distance = 200; position_x = 0; position_y = 0; position_z = 0; light = new THREE.PointLight(color, int ...

serialize the object to JSON format and store it in SharedPreferences

Is my approach correct? I'm trying to save the cards array (object) using SharedPreferences when the back button is pressed, but I keep encountering an error whenever I run the program. Should I convert the object at onCreate instead? @Override p ...

AngularJS Web-app: Display error page if JavaScript is disabled in the browser

If a user has disabled JavaScript in their browser, I want to display an error message indicating that my AngularJS WebApp cannot be viewed. My initial approach is to display this error message by default and replace it with my Angular start page once Jav ...

What is the best way to pass $http and $scope using require?

.controller('Ctrlajax', ['$scope', 'version','$sce', '$resource', '$http', function ($scope, version,$sce,$resource,$http) { $scope.answer = 'Waiting for response from the server.....& ...

Retrieving Radio Button Values from a DataTable with Paginated Pages (Shiny)

I'm encountering an issue with accessing radio button values within a data table in Shiny when using the paging = TRUE option. I've tried implementing code based on this example: Radio Buttons in DT The functionality works fine for me on the ini ...