I am writing a C# wrapper for a RESTful JSON API, and using Json.NET to deserialize the incoming json to strongly typed object. but a few properties in the incoming json are highly dynamic, it will be some json object with different number and type of properties. My current solution is, I mapped the dynamic json property to Dictionary<string, object>
(Nested dictionary) in my C# class,and write Custom JsonConverter to convert dynamic json to Nested dictionary. My class look like this:
public class Item
{
[JsonProperty("item_id")]
public int ItemId { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
//Property to map dynamic json object
[JsonProperty("data")]
public Dictionary<string, object> Data { get; set; }
}
It was successful.
The problem is, its very difficult to to access data from this nested dictionary for the end users, we can't even see what is the structure of data without debugging it in Visual studio. Now i am planning to use JObject or JArray instead of nested dictionary. So that we can see the structure of data by just calling ToString method (Will output the original json data as string) as well as this types have LINQ support so that users can access data from it easily.
Is this a good practice use this, considering JObject and JArray types both depend on a third party library (Anyway Json.NET is a dependency for my library because i am using it for json serialization) . Or there some other ways to do this ?
You should use ExpandoObjectConverter
instead.
You need to type your IDictionary<string, object>
as just dynamic
and decorate the whole property with [JsonConverter(typeof(ExpandoObjectConverter))]
.
One interesting detail is ExpandoObject
also implements IDictionary<string, object>
, but when you type it with dynamic
, you can access associated properties like regular ones! ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With