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

Implement Authorization in Swagger with Static Value in Header .Net 8

If you want an anonymous user should not run the APIs. To run your API Endpoints From Swagger / Postman / Code the user should pass the head...