loop through a jsondocument type in csharp

To loop through a JSON document in C#, you can deserialize the JSON into a dynamic object or a strongly-typed class using the JsonConvert.DeserializeObject method from the Newtonsoft.Json library. Once you have the deserialized JSON object, you can iterate over its properties or elements using traditional loop constructs.

Here's an example of how to loop through a JSON document in C#:

main.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

// Define a class to match your JSON structure
public class Data
{
    public string Name { get; set; }
    public int Age { get; set; }
    // other properties
}

class Program
{
    static void Main(string[] args)
    {
        string json = @"{
            'Name': 'John',
            'Age': 30,
            'Gender': 'Male'
        }";

        // Deserializing JSON into a strongly typed object
        Data data = JsonConvert.DeserializeObject<Data>(json);

        // Loop through properties of the data object
        foreach (var property in typeof(Data).GetProperties())
        {
            Console.WriteLine($"{property.Name}: {property.GetValue(data)}");
        }
    }
}
759 chars
33 lines

In this example, we define a Data class to match the structure of the JSON document. We then deserialize the JSON using JsonConvert.DeserializeObject<Data>(json). Finally, we loop through the properties of the Data object and print their names and values.

Note that you need to install the Newtonsoft.Json package from NuGet in order to use the JsonConvert class.

I hope this helps!

related categories

gistlibby LogSnag