Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you are happy to have a dependency upon the <code>System.Web.Helpers</code> assembly, then you can use the <a href="http://msdn.microsoft.com/en-us/library/system.web.helpers.json(v=vs.111).aspx" rel="noreferrer"><code>Json</code></a> class:</p> <pre><code>dynamic data = Json.Decode(json); </code></pre> <p>It is included with the MVC framework as an <a href="https://stackoverflow.com/q/8037895/24874">additional download</a> 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.</p> <hr> <p>An alternative deserialisation approach is suggested <a href="http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx" rel="noreferrer">here</a>. I modified the code slightly to fix a bug and suit my coding style. All you need is this code and a reference to <code>System.Web.Extensions</code> from your project:</p> <pre><code>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&lt;string, object&gt; dictionary, Type type, JavaScriptSerializer serializer) { if (dictionary == null) throw new ArgumentNullException("dictionary"); return type == typeof(object) ? new DynamicJsonObject(dictionary) : null; } public override IDictionary&lt;string, object&gt; Serialize(object obj, JavaScriptSerializer serializer) { throw new NotImplementedException(); } public override IEnumerable&lt;Type&gt; SupportedTypes { get { return new ReadOnlyCollection&lt;Type&gt;(new List&lt;Type&gt;(new[] { typeof(object) })); } } #region Nested type: DynamicJsonObject private sealed class DynamicJsonObject : DynamicObject { private readonly IDictionary&lt;string, object&gt; _dictionary; public DynamicJsonObject(IDictionary&lt;string, object&gt; dictionary) { if (dictionary == null) throw new ArgumentNullException("dictionary"); _dictionary = dictionary; } public override string ToString() { var sb = new StringBuilder("{"); ToString(sb); return sb.ToString(); } private void ToString(StringBuilder sb) { var firstInDictionary = true; foreach (var pair in _dictionary) { if (!firstInDictionary) sb.Append(","); firstInDictionary = false; var value = pair.Value; var name = pair.Key; if (value is string) { sb.AppendFormat("{0}:\"{1}\"", name, value); } else if (value is IDictionary&lt;string, object&gt;) { new DynamicJsonObject((IDictionary&lt;string, object&gt;)value).ToString(sb); } else if (value is ArrayList) { sb.Append(name + ":["); var firstInArray = true; foreach (var arrayValue in (ArrayList)value) { if (!firstInArray) sb.Append(","); firstInArray = false; if (arrayValue is IDictionary&lt;string, object&gt;) new DynamicJsonObject((IDictionary&lt;string, object&gt;)arrayValue).ToString(sb); else if (arrayValue is string) sb.AppendFormat("\"{0}\"", arrayValue); else sb.AppendFormat("{0}", arrayValue); } sb.Append("]"); } else { sb.AppendFormat("{0}:{1}", name, value); } } sb.Append("}"); } public override bool TryGetMember(GetMemberBinder binder, out object result) { if (!_dictionary.TryGetValue(binder.Name, out result)) { // return null to avoid exception. caller can check for null this way... result = null; return true; } result = WrapResultObject(result); return true; } public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) { if (indexes.Length == 1 &amp;&amp; indexes[0] != null) { if (!_dictionary.TryGetValue(indexes[0].ToString(), out result)) { // return null to avoid exception. caller can check for null this way... result = null; return true; } result = WrapResultObject(result); return true; } return base.TryGetIndex(binder, indexes, out result); } private static object WrapResultObject(object result) { var dictionary = result as IDictionary&lt;string, object&gt;; if (dictionary != null) return new DynamicJsonObject(dictionary); var arrayList = result as ArrayList; if (arrayList != null &amp;&amp; arrayList.Count &gt; 0) { return arrayList[0] is IDictionary&lt;string, object&gt; ? new List&lt;object&gt;(arrayList.Cast&lt;IDictionary&lt;string, object&gt;&gt;().Select(x =&gt; new DynamicJsonObject(x))) : new List&lt;object&gt;(arrayList.Cast&lt;object&gt;()); } return result; } } #endregion } </code></pre> <p>You can use it like this:</p> <pre><code>string json = ...; var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); dynamic obj = serializer.Deserialize(json, typeof(object)); </code></pre> <p>So, given a JSON string:</p> <pre><code>{ "Items":[ { "Name":"Apple", "Price":12.3 }, { "Name":"Grape", "Price":3.21 } ], "Date":"21/11/2010" } </code></pre> <p>The following code will work at runtime:</p> <pre><code>dynamic data = serializer.Deserialize(json, typeof(object)); data.Date; // "21/11/2010" data.Items.Count; // 2 data.Items[0].Name; // "Apple" data.Items[0].Price; // 12.3 (as a decimal) data.Items[1].Name; // "Grape" data.Items[1].Price; // 3.21 (as a decimal) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload