Search code examples
c#asp.netjsonc#-4.0json.net

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"};

Solution

  • [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}
        }
    }