Is there a way to deserialize JSON content into a C# 4 dynamic type? It would be nice to skip creating a bunch of classes in order to use the DataContractJsonSerializer.
|
Unfortunately the blog post by Nikhil Kothari doesn't work with .NET 4 RTM. An alternative deserialisation approach is suggested here. I modified the code slightly to fix a bug and suit my coding style. All you need is this:
You can use it like this:
So, given a JSON string:
The following code will work at runtime:
I'm interested in any discussion about this approach. EDIT I updated the code to fix a small bug (with lists of complex types) and to include a EDIT 2 If you are happy to have a dependency upon the |
|||||||||||||||||||||
|
You can do this using System.Web.Helpers.Json - its Decode method returns a dynamic object which you can traverse as you like. It's included in the System.Web.Helpers assembly (.NET 4.0).
|
|||||||||||||||||
|
It's pretty simple using Json.NET:
Also
|
||||
|
.Net 4.0 has a built-in library to do this:
This is the simplest way. |
|||||||||||||||||||||
|
JsonFx can deserialize json into dynamic objects. |
|||||||||||||
|
I made a new version of the DynamicJsonConverter that uses Expando Objects. I used expando objects because I wanted to Serialize the dynamic back into json using Json.net.
|
|||
|
Simple "string json data" to object without any third party dll
|
|||||
|
Nikhil Kothari blogged about doing this. He included a link to his library which provides a dynamic implementation of a REST client, which works on JSON data. He also has a JSON client that works off strings of JSON data directly. |
|||||||
|
For that I would use JSON.NET to do the low-level parsing of the JSON stream and then build up the object hierarchy out of instances of the |
|||
|
Its probably a little late to help you but the object you want DynamicJSONObject is included in the System.Web.Helpers.dll from the ASP.NET Web Pages package, which is part of WebMatrix. |
|||
|
There is a lightweight json library for C# called SimpleJson which can be found at It supports .net 3.5+, silverlight and windows phone 7. Supports dynamic for .net 4.0 Can also be installed as a nuget package
|
||||
|
Simplest way is Just include this dll use the code like this
|
|||
|
You can extend the JavaScriptSerializer to recursively copy the dictionary it created to expando object(s) and then use them dynamically:
Then you just need to having a using statement for the namespace you defined the extension in (consider just defining them in System.Web.Script.Serialization... another trick is to not use a namespace, then you don't need the using statement at all) and you can consume them like so:
|
||||
|
Another way using Newtonsoft.Json:
|
|||
|