Create Json dynamically in c#
[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} }}
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 }
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"}