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

Enum with Flag Attribute in .NET

In .NET, you can use the Flags attribute with an enum. You can combine multiple values into one to represent a set of bit fields. It is use...