I need to create a Json object dynamically by looping through columns. so declaring an empty json object then add elements to it dynamically.
eg:
List<String> columns = new List<String>{"FirstName","LastName"}; var jsonObj = new {}; for(Int32 i=0;i<columns.Count();i++) jsonObj[col[i]]="Json" + i;
And the final json object should be like this:
jsonObj={FirstName="Json0", LastName="Json1"};
Yes, we can create a JSON object dynamically in C# without creating a class object. In C# application using newtonsoft library, makes working with JSON very easy. First, we have to add Newtonsoft from the NuGet package manager into our project. Then add namespaces Newtonsoft.
A dynamic JSON file will be created to store the array of JSON objects. Consider, we have a database named gfg, a table named userdata. Now, here is the PHP code to fetch data from database and store them into JSON file named gfgfuserdetails. json by converting them into an array of JSON objects.
[TestFixture] public class DynamicJson { [Test] public void Test() { dynamic flexible = new ExpandoObject(); flexible.Int = 3; flexible.String = "hi"; var dictionary = (IDictionary<string, object>)flexible; dictionary.Add("Bool", false); var serialized = JsonConvert.SerializeObject(dictionary); // {"Int":3,"String":"hi","Bool":false} } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With