JSON parsing in C#

I'm struggling to parse JSON in c# that is structured like the example below. The code snippet I have been using is somewhat functional, but it lacks stability.

(I'm also looking for guidance on how to parse JSON in Javascript, which is another task on my plate.)

Take a look at the JSON format I am working with:

{"72": { "Rejected": true }, "271": { "PreApproved": true}}

Here's a snippet of the code I've been working with:

List<SSKChanges> lstSSK = new List<SSKChanges>();
string sskSource = "";
string sskStatus = "";
bool sskStatusBool = false;
int i = 0;
int iList = 0;
JsonTextReader reader = new JsonTextReader(new StringReader(jsonExample));
while (reader.Read())
{
    if (reader.Value != null)
    {
        if (i == 0)
        {
            int n;
            bool isNumeric = int.TryParse(reader.Value.ToString(), out n);
            if (isNumeric)
            {
                sskSource = reader.Value.ToString();
                i = 1;
            }
            else
            {
                sskStatus = reader.Value.ToString();
                i = 2;
            }
        }
        else if (i == 1)
        {
            sskStatus = reader.Value.ToString();
            i = 2;
        }
        else
        {
            sskStatusBool = (bool)reader.Value;
            i = 0;
            sskSource = "";
            sskStatus = "";
            sskStatusBool = false;
        }
    }
}

Answer №1

If you're already utilizing json.net (which seems to be implied by your reference to 's JsonTextReader), you can import your JSON data into a JObject and then utilize LINQ to JSON to query the object.

For example, consider the following class:

public class SSKChanges
{
    public string SskSource { get; set; }
    public string SskStatus { get; set; }
    public bool? SskStatusBool { get; set; }
}

You can perform the following:

        var obj = JObject.Parse(jsonExample);
        var lstSSK = (from property in obj.Properties()
                      select new SSKChanges
                      {
                          SskSource = property.Name,
                          SskStatus = property.Value.Children<JProperty>().Select(p2 => p2.Name).FirstOrDefault(),
                          SskStatusBool = property.Value.Children<JProperty>().Select(p2 => (bool?)p2.Value).FirstOrDefault()
                      }).ToList();

Regarding your additional query in your question, about not knowing how to parse in JavaScript and needing assistance with that, it might be best to post a separate question specifically for JavaScript experts.

Answer №2

If you're already working with Json.net, consider utilizing it like this:

string json = @"{""72"": { ""Rejected"": true }, ""271"": { ""PreApproved"": true}}";
var jobj = JObject.Parse(json);

foreach (var entry in jobj.Children().Cast<JProperty>())
{
    var kv = entry.Value.First() as JProperty;
    Console.WriteLine(entry.Name + "=>" + kv.Name + ":"  + kv.Value);
}

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

What is the method to fetch a JSON URL data set (using Ajax and jQuery) in order to generate a dynamic chart display that updates automatically on a Wordpress webpage?

I have downloaded all the necessary plugins for Wordpress, but unfortunately, the data is not displaying. Below is the code I am using to embed the data onto a page: <script> <div class="result"></div> <script type="text/javascri ...

What is the best approach for retrieving a User from my Angular front-end service?

INQUIRY: I'm attempting to retrieve the details of the currently logged in user in my Angular 2 frontend service with the following code: UserModel.findById(userID, function (err, user) { It appears that this behavior is achievable from the browse ...

Encountering the "EHOSTUNREACH" error message while attempting to establish a connection to an API through the combination of Axios and Express

Exploring the capabilities of the Philips Hue Bridge API, I delved into sending requests using Postman. To my delight, I successfully authenticated myself, created a user, and managed to toggle lights on and off. Verdict: Accessing the API is achievable. ...

Issue with Google Tag Manager click event not propagating to parent element

I am currently configuring Google Tag Manager for a client's website and encountering difficulties in getting click event tags to activate. Although I have set the trigger to activate based on the button's CSS selector, the actual button contain ...

Instructions for transferring numerous chosen files (such as .doc, .pdf, .jpeg, .png) to a server from an Android device

Can you provide guidance on selecting multiple files from a file manager in Android? Once the details of the image are displayed (such as image size, name, and the option to delete the files), how can we upload these files to a server? ...

Press the button to automatically scroll to a designated div section

One of the challenges I'm facing involves a fixed menu and content box (div) on a webpage. Whenever I click on the menu, the content box should scroll to a specific div. Initially, everything was working fine. Here is a sample of it in action: http ...

Problem with sortable columns in DataTables

$(document).ready(function () { var dt = $('#example').DataTable({ "processing": true, "serverSide": true, "ajax": "api.php?t=clients", "columns": [{ "className": "details-control", ...

Angular Card Flip Directive and Its Isolated Scope

In my AngularJs project, I am working on a directive to achieve card flipping functionality. Using HTML(Jade) card display | this is sid input.btn.btn-primary(type='submit', value=&apos ...

Guide on extracting the keys from an object_construct and displaying them in their own distinct column

My data is structured in a table format. Here is an example: ID ALL_ATTRIBUTES ALL_FIELDS 1 {"name" : "JESSICA"} {"name"} 2 {"age": 15, "name": "JOSH"} {"age", "name" ...

Tips for utilizing playFromPositionAsync method with expo-av Video in React Native

While working with the Video Expo component, I came across a prop called playFromPositionAsync. In the Video.d.ts file, it is defined like this: export default class Video extends React.Component<VideoProps, VideoState> implements Playback { ... ...

The appearance of an escape character has been detected within the JSON output

Currently, I am facing an issue while writing to an Avro file that is being sent to Snowflake. One of the fields in this process contains a blob of JSON data. The JSON structure consists of various elements and values, and its format is dynamic and unknow ...

Storing a temporary value within an ng-repeat iteration in AngularJS

A unique and interesting query arises when dealing with random value generation. Here is a snippet of code that showcases how to achieve this: function randomize() { return function (input) { if (input !== null && input !== undefined & ...

Ways to attach an item using its lower point instead of its upper coordinate

I am currently working on a poker table project using React. As of now, I have player components that need to be strategically positioned around the table. https://i.sstatic.net/gX9Ij.png One challenge I'm facing is that when the screen attribute ch ...

Utilize angular to call a function when navigating

Having an issue with ChartJS while creating a chart using angular. The problem arises when navigating to a new page and then back to the original one, as the JavaScript is not triggered again. Is there a way to automatically invoke a JavaScript function o ...

I keep encountering a 404 error page not found whenever I try to use the useRouter function. What could

Once the form is submitted by the user, I want them to be redirected to a thank you page. However, when the backend logic is executed, it redirects me to a 404 page. I have checked the URL path and everything seems to be correct. The structure of my proje ...

Unable to transfer a file to an FTP server if it is currently being edited by another application in C#

I am currently working on a project that involves monitoring a specific file on my computer and automatically uploading it to my FTP server whenever the file's content changes. However, I am running into the issue of not being able to upload the file ...

There are multiple 'ConvertFromString' methods for the type that are compatible with the provided arguments

My CsvBool converter is public class CsvBool : BooleanConverter { public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData) { if (value == null) return string.Empty; ...

What is the best way to share dynamic content from a DIV or SPAN element on WhatsApp using jQuery?

I’ve been attempting to share the text content of a specific DIV on WhatsApp, but so far I haven't been successful. My goal is to only share a portion of the document (specifically the contents of showques). Below is the code snippet I've been ...

Running an ESNext file from the terminal: A step-by-step guide

Recently, I delved into the world of TypeScript and developed an SDK. Here's a snippet from my .tsconfig file that outlines some of the settings: { "compilerOptions": { "moduleResolution": "node", "experimentalDecorators": true, "module ...

Obtain the Model linked to the relevant View using HtmlHelper

My perspective involves inheriting Models.MyModel <%@ Page Language="C#" MasterPageFile="Something.Master" Inherits="Models.MyModel>" %> I am looking for a way to have the property Model.Something accessible in an HtmlHelper method when I invoke ...