title: Printing Contents of ExpandoObject to an Indented String
body: <p>I am currently working on a program that takes JSON input and deserializes it using JSON.NET into a dynamic ExpandoObject. Then through a function, I want to dump it out into another textbox to show what it could possibly represent as C# objects. How would I indent my string to show my hierarchical ExpandoObject and take it from a flat list of data to a tree structure of data I can send to a textbox as a string?</p>
  
  <p>Here is some of the code I am using:</p>
  
  <pre><code>if (tbxJSON.Text != "")
  {
          // Create an ExpandoObjectConverter in order to hold the dynamic parsed JSON.
          var converter = new ExpandoObjectConverter();
          dynamic convertedJSON = JsonConvert.DeserializeObject&lt;ExpandoObject&gt;(tbxJSON.Text, converter);
  
              tbxCSharp.Text = "";
  
          // Loop through the ExpandoObject and print out all of the values in the dynamic object using a recursive function.
          foreach (var property in (IDictionary&lt;string, object&gt;)convertedJSON)
                  sb.Append(ExpandoToString(property.Value, property.Key));
  
          // Set C# output to contents of StringBuilder.
          tbxCSharp.Text = sb.ToString();
  }
  
  private string ExpandoToString(object propVal, string propName)
  {
      string retStr = "";
  
      // If we are dealing with nested JSON
      if (propVal.GetType() == typeof(ExpandoObject))
      {
          // Append this object type.
          sb.Append(Indent(indentIdx) + UppercaseFirst(propName) + " " + propName + " consists of..." + Environment.NewLine);
  
          foreach (var prop in (IDictionary&lt;string, object&gt;)propVal)
          {
              if (prop.Value.GetType() == typeof(ExpandoObject))
                  sb.Append(ExpandoToString(prop.Value, prop.Key));
              else
              {
                  if (prop.Value.GetType() == typeof(List&lt;dynamic&gt;))
                  {
                      // TO DO
                  }
                  else
                      sb.Append(ExpandoToString(prop.Value, prop.Key));
              }
          }
      }
      else 
              retStr = propVal.GetType() + " : " + propName + " = " + propVal + Environment.NewLine;
  
      return retStr;
  }
  
  
  Test JSON:
  {"airline":"Oceanic","number":815,"departure":{"IATA":"SYD","time":"2004-09-22 14:55","city":"Sydney"},"arrival":{"IATA":"LAX","time":"2004-09-23 10:42","city":"Los Angeles"}}
  </code></pre>