It turns out I am solving the same exact problem. I've worked it out after a lot of researching Stack Overflow.
What you need is a helper class to get JArrays out of JSON objects. That looks like this:
public static JArray ToJArray(this JToken token, string itemProperty)
{
if (token != null && token.Type != JTokenType.Null)
{
token = token[itemProperty];
if (token != null)
{
if (token.Type == JTokenType.Array)
{
return (JArray)token;
}
else
{
return new JArray(token);
}
}
}
return new JArray();
}
The source code for the above was from this StackOverflow article: Link
Next you have to keep in mind that you still get the root object in your data. you have to work around it. In the link above, you'll see his source looks like this. It demos how to use it.
class Program
{
static void Main(string[] args)
{
string json = @"
{
""collection1"": {
""item"": {
""label"": ""A"",
""value"": ""1""
}
},
""collection2"": {
""item"": [
{
""label"": ""B"",
""value"": ""2""
},
{
""label"": ""C"",
""value"": ""3""
}
]
},
""collection3"": null
}";
JObject root = JObject.Parse(json);
DumpItems(root, "collection1");
DumpItems(root, "collection2");
DumpItems(root, "collection3");
}
private static void DumpItems(JToken token, string collectionName)
{
JArray array = token[collectionName].ToJArray("item");
Console.WriteLine("Count of items in " + collectionName + ": " + array.Count);
foreach (JToken item in array)
{
Console.WriteLine(item["label"] + ": " + item["value"]);
}
}
}
Here is my example of how I worked around that 'results' root. In my example, each item in the list contains an ID, a Name, and a Tags string.
public List GetResultsWithTag(string tagSrc)
{
// the Results object in the json data is a JObject. It contains a JSON Array of Result objects
JObject root = JObject.Parse(jsonData);
JArray array = DumpItems(root, "results");
List<Result> returnList = new List<Result>();
foreach(var item in array)
{
Debug.WriteLine(item.ToString());
Result _result = new Result();
_result.ID = item["ID"].ToString();
_result.Name = item["Name"].ToString();
_result.Tags = item["Tags"].ToString();
if(_result.Tags.Contains(tagSrc))
{
returnList.Add(_result);
}
}
return returnList;
}
feature? What type isitem? What type isResponseobj?