Alaa Osta
Alaa Osta

Reputation: 4339

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

Upvotes: 47

Views: 116170

Answers (4)

Andrew
Andrew

Reputation: 20111

Using dynamic and JObject:

dynamic obj = new JObject();
obj.ProductName = "Elbow Grease";
obj.Enabled = true;
obj.StockCount = 9000;

Another way to assign properties:

var obj = new JObject();
obj["ProductName"] = "Elbow Grease";
obj["Enabled"] = true;
obj["StockCount"] = 9000;

Or using JObject.FromObject:

JObject obj = JObject.FromObject(new
{
    ProductName = "Elbow Grease",
    Enabled = true,
    StockCount = 9000
});

They all produce this result:

Console.WriteLine(obj.ToString());
// {
//   "ProductName": "Elbow Grease",
//   "Enabled": true,
//   "StockCount": 9000
// }

https://www.newtonsoft.com/json/help/html/CreateJsonDynamic.htm

Upvotes: 12

ghiscoding
ghiscoding

Reputation: 13214

I found a solution very similar to DPeden, though there is no need to use the IDictionary, you can pass directly from an ExpandoObject to a JSON convert:

dynamic foo = new ExpandoObject();
foo.Bar = "something";
foo.Test = true;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);

and the output becomes:

{ "FirstName":"John", "LastName":"Doe", "Active":true }

Upvotes: 22

David Peden
David Peden

Reputation: 18464

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

Upvotes: 62

Mathew Thompson
Mathew Thompson

Reputation: 56449

You should use the JavaScriptSerializer. That can Serialize actual types for you into JSON :)

Reference: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

EDIT: Something like this?

var columns = new Dictionary<string, string>
            {
                { "FirstName", "Mathew"},
                { "Surname", "Thompson"},
                { "Gender", "Male"},
                { "SerializeMe", "GoOnThen"}
            };

var jsSerializer = new JavaScriptSerializer();

var serialized = jsSerializer.Serialize(columns);

Output:

{"FirstName":"Mathew","Surname":"Thompson","Gender":"Male","SerializeMe":"GoOnThen"}

Upvotes: 23

Related Questions