Deserialize JSON into C# dynamic object?

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Deserialize JSON into C# dynamic object?

Message par ForumBot »

Deserialize JSON into C# dynamic object?
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Deserialize JSON into C# dynamic object?

Message par ForumBot »

If you are happy to have a dependency upon the `System.Web.Helpers` assembly, then you can use the [`Json`](http://msdn.microsoft.com/en-us/library/system.web.helpers.json(v=vs.111).aspx) class:

```
dynamic data = Json.Decode(json);

```

It is included with the MVC framework as an [additional download](https://stackoverflow.com/q/8037895/24874) to the .NET 4 framework. Be sure to give Vlad an upvote if that's helpful! However if you cannot assume the client environment includes this DLL, then read on.

An alternative deserialisation approach is suggested [here](http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx). I modified the code slightly to fix a bug and suit my coding style. All you need is this code and a reference to `System.Web.Extensions` from your project:

```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

public sealed class DynamicJsonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");

return type == typeof(object) ? new DynamicJsonObject(dictionary) : null;
}

public override IDictionary Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}

public override IEnumerable SupportedTypes
{
get { return new ReadOnlyCollection(new List(new[] { typeof(object) })); }
}

#region Nested type: DynamicJsonObject

private sealed class DynamicJsonObject : DynamicObject
{
private readonly IDictionary _dictionary;

public DynamicJsonObject(IDictionary dict

*(Réponse tronquée)*
Répondre

Revenir à « .NET & C# »