I was lately trying to deserialize JSON content using JSON.Net API with dynamic datatype.
I searched the forum really hard and found out that it is indeed possible to do so in WinRT.
A sample JSON could be:
string json = "{\"message\":\"Sample Message\"}"
I used the following format:
dynamic result = JsonConvert.DeserializeObject<dynamic>(json);
It successfully deserializes the content to result. But when I try to access it using a syntax like:
string message = result.message;
It results in an error which is:
‘object’ does not contain a definition for ‘message’ and no extension method ‘message’ accepting a first argument of type ‘object’ could be found (are you missing a using directive or an assembly reference?)
I tried with many json samples all over the internet but the error remains the same.
Truly speaking, I tried it a some hours back it ACTUALLY worked! But I couldn’t find what I am missing this time.
PS: I need to use dynamic only because my actual Json contains dynamic field names.
Once it is like:
{"New York" : "Its in United States"}
And sometimes it is like:
{"London" : "Its in United Kingdom"}
(Crap example though! 😛 )
The json2csharp classes method won’t work here I guess and if there is some secondary and more efficient method. Please guide me in. The real Json which I am trying to parse is very complex. I would post it if it needs to be posted.
I use JSON.NET in a personal project of mine, but deserialize using square bracket syntax like this:
To actually get the JSON object I do this:
I adopted this methodology after doing a good bit of research into the different ways to use JSON.NET. I seriously considered going the dynamic route after reading this article: http://www.west-wind.com/weblog/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing
However, in the end I decided against dynamic objects because when I fill my normal objects with the square bracket syntax I return immediately to a strongly-typed environment where intellisense will begin to catch any errors I may make. I combine this with a LINQ query and fill a set of fairly complex objects in a relatively few number of lines.
For me, dynamic objects are one more weakly-typed step in the deserialization process that I prefer to avoid if possible.