<p>Si vous acceptez d’avoir une dépendance envers l’assembly <code>System.Web.Helpers</code>, vous pouvez utiliser la classe <a href="http://msdn.microsoft.com/en-us/library/system.web.helpers.json(v=vs.111).aspx"><code>Json</code></a> :</p>
<pre><code class="lang-auto">dynamic data = Json.Decode(json);
</code></pre>
<p>Elle est incluse avec le framework MVC en tant que <a href="https://stackoverflow.com/q/8037895/24874">téléchargement supplémentaire</a> au framework .NET 4. N’oubliez pas de donner un vote positif à Vlad si c’est utile ! Cependant, si vous ne pouvez pas garantir que l’environnement client inclut cette DLL, alors continuez la lecture.</p>
<p>Une approche de désérialisation alternative est suggérée <a href="http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx">ici</a>. J’ai légèrement modifié le code pour corriger un bug et l’adapter à mon style de codage. Tout ce dont vous avez besoin est ce code et une référence à <code>System.Web.Extensions</code> depuis votre projet :</p>
<pre><code class="lang-auto">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<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
return type == typeof(object) ? new DynamicJsonObject(dictionary) : null;
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { typeof(object) })); }
}
#region Nested type: DynamicJsonObject
private sealed class DynamicJsonObject : DynamicObject
{
private readonly IDictionary<string, object> _dictionary;
public DynamicJsonObject(IDictionary<string, object> dict
(Réponse tronquée)</code></pre>