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
Author by
Alaa Osta
Updated on July 09, 2022Comments
-
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 about 12 yearsI'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 about 12 yearsOded because it's available in the .Net framework. No 3rd party DLL required.
-
Oded about 12 years@SpencerRuport - Not everything that comes with the BCL is the best of breed.
-
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 about 12 yearsI 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 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 about 12 yearsJust so I know, what types are your columns?
-
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 about 12 years@mattytommo can you check my example again please
-
Alaa Osta about 12 yearsYape that is what I am looking for, thanks.I will try it and get back with you
-
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 over 11 yearsI 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 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 over 8 yearsIs 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 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 almost 5 yearsThis is is best and easy solution
-
n4rzul about 4 yearsThat is not what they asked for. Their attribute names exist as strings in a list. Your attributes are hard coded.
-
n4rzul about 4 yearsThis isn't exactly what they asked for. Their property names exist in strings in a list. You just hardcoded Bar and Test.
-
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 over 3 yearsActually, @ghiscoding, I think @n4rzul is right. You cannot add fields from a string in this way:
dictionary.Add(myFieldName, false);
with your solution. -
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 over 3 yearsThe dictionary is not needed AFAICT. I also go to the convert directly from the expando...