title: Flattening out a JToken
body: <p>Suppose I have the following JToken:</p>
  
  <pre><code>@"{
      ""data"": [
          {
              ""company"": {
                  ""ID"": ""12345"",
                  ""location"": ""Some Location""
              },
              ""name"": ""Some Name""
          }
      ]
  }";
  </code></pre>
  
  <p>I want to pass this token into a FlattenToken function that outputs this JToken:</p>
  
  <pre><code>@"{
      ""data"": [
          {
              ""company_ID"": ""12345"",
              ""company_location"": ""Some Location"",
              ""name"": ""Some Name""
          }
  ]}"
  </code></pre>
  
  <p>The reason for doing this is so that I can then take the flattened JToken and deserialize it into a DataTable.</p>
  
  <p>I'm getting lost in a jumble of JObjects, JTokens, JProperties, and other JMadness, though. I saw the answer on <a href="https://stackoverflow.com/questions/15413825/how-do-you-add-a-jtoken-to-an-jobject">this post</a>, which was helpful, but I'm still not getting it right.</p>
  
  <p>Here's what I have so far:</p>
  
  <pre><code>public static JToken FlattenToken(JToken token)
  {
      foreach (JToken topLevelItem in token["data"].Children())
      {
          foreach (JToken field in topLevelItem.Value&lt;JToken&gt;())
          {
              foreach (JProperty property in field.Value&lt;JObject&gt;().Properties())
              {
                  field.AddAfterSelf(JObject.Parse(@"{""" + property.Name + "_" + property.Value));
              }
  
              field.Remove();
          }
      }
  
      return token;
  }
  </code></pre>
  
  <p>The first iteration through the outer foreach loop, topLevelItem =</p>
  
  <pre><code>{
      "company": {
          "ID": "12345"
      },
      "name": "Some Name"
  }
  </code></pre>
  
  <p>And the first iteration through the second foreach loop, field = </p>
  
  <pre><code>"company": {
      "ID": "12345"
  }
  </code></pre>
  
  <p>Looking good so far. But when I hit the innermost foreach loop, I get an exception on the foreach line: "Cannot cast Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JToken."</p>
  
  <p>Not sure what's going on there. I was under the impression that the field.Value call was going to produce a JToken and try to cast it to a JProperty. So where is a JProperty trying to be casted to a JToken, as the error suggests?</p>
  
  <p>Also, this feels like a pretty gross way of flattening out a JToken. Is there a better way?</p>