Thursday, 27 June 2024

C# Create Dynamic JSON With Dynamic Keys

 In this article, we will create a dynamic JSON.

When you have a requirement where you are not sure how many nodes/keys you need to create in the JSON then follow the below approach.


Step 1: Declare a dictionary

            var fileData = new Dictionary<string, object>();


Step 2: Add dynamic data, in my example, I have an array of nodes and values. So, I am adding values to each.

 foreach (DocumentKeyValuePair kvp in result.KeyValuePairs)

 {

             fileData[kvp.Key.Content] = kvp.Value.Content;     

 }


Step 3: Searlize Object using Newtonsoft.Json;


 string json = JsonConvert.SerializeObject(fileData, Formatting.Indented);

 System.IO.File.WriteAllText(@"D:\file.json", json);



I am also saving the JSON in D drive, you can specify your path.

Your file will be saved in the specific directory and you can see I have dynamic keys and values.




No comments:

Post a Comment

Create an Azure AD B2C (ADB2C) user using Postman

 Here's a step-by-step guide to help you through the process. Registered App in Azure AD B2C with: Delegated Microsoft Graph API...