Create Json dynamically in c#

83,702

Solution 1

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

Solution 2

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 }

Solution 3

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

Solution 4

Using dynamic and JObject

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

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

Or how about:

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

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

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

Share:
83,702
Alaa Osta
Author by

Alaa Osta

Updated on July 09, 2022

Comments

  • Alaa Osta
    Alaa Osta almost 2 years

    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"};
    
  • mattytommo
    mattytommo about 12 years
    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 :)
  • rookie
    rookie about 12 years
    Oded because it's available in the .Net framework. No 3rd party DLL required.
  • Oded
    Oded about 12 years
    @SpencerRuport - Not everything that comes with the BCL is the best of breed.
  • mattytommo
    mattytommo about 12 years
    @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 :)
  • Alaa Osta
    Alaa Osta about 12 years
    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.
  • mattytommo
    mattytommo about 12 years
    @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 :)
  • mattytommo
    mattytommo about 12 years
    Just so I know, what types are your columns?
  • Alaa Osta
    Alaa Osta about 12 years
    @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
    Alaa Osta about 12 years
    @mattytommo can you check my example again please
  • Alaa Osta
    Alaa Osta about 12 years
    Yape that is what I am looking for, thanks.I will try it and get back with you
  • mattytommo
    mattytommo about 12 years
    @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?
  • Farrukh Subhani
    Farrukh Subhani over 11 years
    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.
  • mattytommo
    mattytommo over 11 years
    @FarrukhSubhani Yeah it can be put into a function, the datatype of the serialized variable is string, check here for reference: msdn.microsoft.com/en-us/library/…
  • Teilmann
    Teilmann over 8 years
    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.
  • David Peden
    David Peden over 8 years
    @ThomasTeilmann consider asking a new question with more detail. i'm not sure what you're after based upon your comment.
  • Manjunath Patelappa
    Manjunath Patelappa almost 5 years
    This is is best and easy solution
  • n4rzul
    n4rzul about 4 years
    That is not what they asked for. Their attribute names exist as strings in a list. Your attributes are hard coded.
  • n4rzul
    n4rzul about 4 years
    This isn't exactly what they asked for. Their property names exist in strings in a list. You just hardcoded Bar and Test.
  • ghiscoding
    ghiscoding about 4 years
    @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.
  • tonjo
    tonjo over 3 years
    Actually, @ghiscoding, I think @n4rzul is right. You cannot add fields from a string in this way: dictionary.Add(myFieldName, false); with your solution.
  • n4rzul
    n4rzul over 3 years
    @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.
  • Allen
    Allen over 3 years
    The dictionary is not needed AFAICT. I also go to the convert directly from the expando...