46

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"};
Andrew
  • 18,680
  • 13
  • 103
  • 118
Alaa Osta
  • 4,249
  • 6
  • 24
  • 28

4 Answers4

59
[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}
    }
}
David Peden
  • 17,596
  • 6
  • 52
  • 72
  • Yape that is what I am looking for, thanks.I will try it and get back with you – Alaa Osta Apr 20 '12 at 20:26
  • Is it possible to get something like: { "Schools": [ {"name": "test"}, {"name": "testing"} ] } with the ExpandoObject approach? the array name, Schools in this example, should be a variable. – Teilmann Oct 07 '15 at 07:19
  • @ThomasTeilmann consider asking a new question with more detail. i'm not sure what you're after based upon your comment. – David Peden Oct 07 '15 at 13:01
22

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 }
ghiscoding
  • 12,308
  • 6
  • 69
  • 112
  • 1
    This is is best and easy solution – Manjunath Patelappa May 10 '19 at 14:11
  • 3
    This isn't exactly what they asked for. Their property names exist in strings in a list. You just hardcoded Bar and Test. – n4rzul Apr 20 '20 at 07:59
  • 1
    @n4rzul I don't understand the reason for your downvote when you most probably haven't even tried it. It's only hardcoded for demo purposes, you can replace the hardcode value by any dynamic values. – ghiscoding Apr 21 '20 at 02:48
  • 1
    Actually, @ghiscoding, I think @n4rzul is right. You cannot add fields from a string in this way: `dictionary.Add(myFieldName, false);` with your solution. – tonjo Oct 27 '20 at 10:14
  • 2
    @ghiscoding Please read the exact question carefully. There is a very specific problem they are trying to solve and simply hardcoding Bar and Test does NOT solve their *specific* problem. – n4rzul Nov 19 '20 at 13:23
  • The dictionary is not needed AFAICT. I also go to the convert directly from the expando... – Allen Jan 29 '21 at 15:53
20

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"}
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
  • I'm not aware of json.net, you got a link? I've used JavaScriptSerializer for both serialization and deserialization in the past and it's always served me well :) – Mathew Thompson Apr 20 '12 at 19:57
  • 1
    Oded because it's available in the .Net framework. No 3rd party DLL required. – Spencer Ruport Apr 20 '12 at 19:58
  • @SpencerRuport - Not everything that comes with the BCL is the best of breed. – Oded Apr 20 '12 at 19:59
  • 1
    @Oded I suspect it was a case of mistaken tagging :). What exactly does json.net offer that the JavaScriptSerializer doesn't? I have no problems with using 3rd party tools, as long as the benefit is there. For someone not even sure how to build a JSON string, I think built in .NET behaviour should be more than adequate :) – Mathew Thompson Apr 20 '12 at 20:00
  • I didn't ask to serialize or deserialize please read my case well, I want to create a dynamic Json so I can add elements to it dynamically, if you guys have an example please post it asap. – Alaa Osta Apr 20 '12 at 20:03
  • @AlaaOsta you are actually asking how to serialize items to JSON, albeit adding elements dynamically or any other way :). I'll post an example, give me 10 minutes :) – Mathew Thompson Apr 20 '12 at 20:04
  • Just so I know, what types are your columns? – Mathew Thompson Apr 20 '12 at 20:05
  • @mattytommo OK, I am waiting thanks for ur help. Type of columns is string, just give me the key of building non constant json object and I will complete the rest – Alaa Osta Apr 20 '12 at 20:06
  • @mattytommo can you check my example again please – Alaa Osta Apr 20 '12 at 20:20
  • @AlaaOsta are you expecting an actual object that corresponds to the JSON, or a JSON string? Is there any reason you're both setting the value to the columns and adding them to the JSON at the same time? – Mathew Thompson Apr 20 '12 at 20:31
  • I can see you are using var to create final serialized variable. Can we put this in a function and what would be the return type. I have a helper library and would like to add this to that so i can pass list of columns and list of items and it iterates and generate dynamic json but it should return json so i can use it in many controllers. – Farrukh Subhani Nov 09 '12 at 01:34
  • 1
    @FarrukhSubhani Yeah it can be put into a function, the datatype of the serialized variable is string, check here for reference: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.serialize.aspx – Mathew Thompson Nov 09 '12 at 20:31
11

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

Andrew
  • 18,680
  • 13
  • 103
  • 118