Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Json dynamically in c#

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"}; 
like image 581
Alaa Osta Avatar asked Apr 20 '12 19:04

Alaa Osta


People also ask

How to create JSON file dynamically in C#?

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.

Can JSON be dynamic?

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.


1 Answers

[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}     } } 
like image 141
David Peden Avatar answered Oct 02 '22 23:10

David Peden