Dynamic binding
suggest changeNewtonsoft’s Json.NET allows you to bind json dynamically (using ExpandoObject / Dynamic objects) without the need to create the type explicitly.
Serialization
dynamic jsonObject = new ExpandoObject();
jsonObject.Title = "Merchant of Venice";
jsonObject.Author = "William Shakespeare";
Console.WriteLine(JsonConvert.SerializeObject(jsonObject));
De-serialization
var rawJson = "{\"Name\":\"Fibonacci Sequence\",\"Numbers\":[0, 1, 1, 2, 3, 5, 8, 13]}";
dynamic parsedJson = JObject.Parse(rawJson);
Console.WriteLine("Name: " + parsedJson.Name);
Console.WriteLine("Count: " + parsedJson.Numbers.Count);
Notice that the keys in the raw JSON object have been turned into members of the dynamic object. JArray exposes Count, not Length.
This is useful in cases where an application can accept/ produce varying formats of JSON. It is however suggested to use an extra level of validation for the Json string or to the dynamic object generated as a result of serialization/ de-serialization.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents