title: Decode nested JSON objects in C#
body: <p>I am trying to convert a nested JSON object on an ASP.NET server. The incoming JSON string looks something like this -</p>
  
  <pre class="lang-js prettyprint-override"><code>data: {
     user_id: 1,
     taskid: "1234",
     list: {
         "item-1": { one: 1, two: 2 },
         "item-2": { one: 1, two: 2 }   
         //.. where number of items is unknown
     }
  }
  </code></pre>
  
  <p>I have tried to decode the data using <a href="http://msdn.microsoft.com/en-us/library/system.web.helpers.json.decode%28v=vs.111%29.aspx" rel="nofollow">JSON.Decode</a> this way</p>
  
  <pre><code>public class Data {
      public int user_id { get; set; }
      public string taskid { get; set; }
      public List&lt;object&gt; list { get; set; }
  }
  
  public class DataList {
      List&lt;Data&gt; data { get; set; }
  }
  
  // if isPost etc..
  
  var decodedData = JSON.Decode&lt;DataList&gt;(Request["data"])
  </code></pre>
  
  <p>But when I try and iterate over decodedData I am getting an error -</p>
  
  <blockquote>
    <p>foreach statement cannot operate on variables of type
    'ASP._Page_that_cshtml.DataList' because
    'ASP._Page_that_cshtml.DataList' does not contain a public definition
    for 'GetEnumerator'</p>
  </blockquote>
  
  <p>When I try casting the decodedData to a List this way -</p>
  
  <pre><code>List&lt;Data&gt; decodedData = JSON.Decode&lt;DataList&gt;(Request["data"])
  </code></pre>
  
  <p>I throw another error</p>
  
  <blockquote>
    <p>CS0030: Cannot convert type '<code>ASP._Page_that_cshtml.DataList</code>' to '<code>System.Collections.Generic.List&lt;ASP._Page_that_cshtml.DataList&gt;</code>'</p>
  </blockquote>
  
  <p>Could you please suggest an appropriate method to convert nested JSON objects into a C# object and iterating over it?</p>
  
  <p>PS: trailing semi-colons omitted on-purpose</p>