47

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

4 Answers 4

62
[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}
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yape that is what I am looking for, thanks.I will try it and get back with you
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.
@ThomasTeilmann consider asking a new question with more detail. i'm not sure what you're after based upon your comment.
23

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

12 Comments

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 :)
Oded because it's available in the .Net framework. No 3rd party DLL required.
@SpencerRuport - Not everything that comes with the BCL is the best of breed.
@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 :)
@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/…
|
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 }

6 Comments

This is is best and easy solution
This isn't exactly what they asked for. Their property names exist in strings in a list. You just hardcoded Bar and Test.
@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.
Actually, @ghiscoding, I think @n4rzul is right. You cannot add fields from a string in this way: dictionary.Add(myFieldName, false); with your solution.
@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.
|
12

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

2 Comments

That is not what they asked for. Their attribute names exist as strings in a list. Your attributes are hard coded.
@n4rzul with JObject you can do: obj["FirstName"] = "The Persons Name";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.