Suppose I have the following JToken:
@"{
""data"": [
{
""company"": {
""ID"": ""12345"",
""location"": ""Some Location""
},
""name"": ""Some Name""
}
]
}";
I want to pass this token to the FlattenToken function, which outputs this JToken:
@"{
""data"": [
{
""company_ID"": ""12345"",
""company_location"": ""Some Location"",
""name"": ""Some Name""
}
]}"
The reason for this is that I can take a flattened JToken and deserialize it into a DataTable.
I get lost in the mess of JObjects, JTokens, JProperties and other JMadness. I saw an answer to this post that was useful, but I still don't understand.
Here is what I still have:
public static JToken FlattenToken(JToken token)
{
foreach (JToken topLevelItem in token["data"].Children())
{
foreach (JToken field in topLevelItem.Value<JToken>())
{
foreach (JProperty property in field.Value<JObject>().Properties())
{
field.AddAfterSelf(JObject.Parse(@"{""" + property.Name + "_" + property.Value));
}
field.Remove();
}
}
return token;
}
First iteration through the foreach outer loop, topLevelItem =
{
"company": {
"ID": "12345"
},
"name": "Some Name"
}
And the first iteration through the second foreach loop, field =
"company": {
"ID": "12345"
}
Look good so far. But when I get into the innermost foreach loop, I get an exception in the foreach line: "You cannot use Newtonsoft.Json.Linq.JProperty for Newtonsoft.Json.Linq.JToken."
, . , field.Value JToken JProperty. , JProperty JToken, ?
, JToken. ?