How to see Children().ToList() method in JEnumerable<JToken> object?

19,446

Solution 1

You don't need to use ToList() here.

var results = newsResponse["NewsResponse"]["NewsItems"]["NewsItem"].Children(); 

This will produce an Enumerable (lazy) collection usable with your foreach below.

Note: I'm using var since I don't know the exact type returned here, but we don't really care for it, and it's probably quite complicated, so that's really useful.

Solution 2

Since I am not able to comment on jv42's Answer and since I do not like anonymous types, I will build on his answer a bit.

You should not need to use .ToList() as mentioned above, and the results will become a JEnumerable which can be foreach'ed through:

JEnumerable results = newsResponse["NewsResponse"]["NewsItems"]["NewsItem"].Children();

foreach( JToken result in results )
{
    Console.WriteLine(result.ToString());
}
Share:
19,446
Ivan Byelko
Author by

Ivan Byelko

Updated on June 04, 2022

Comments

  • Ivan Byelko
    Ivan Byelko almost 2 years

    I try to parse JSON by JSON.NET and in App class is OK, but if I want write parse method in custom class, VS don't see method ToList() in JEnumerable<JToken> object.

    Listing:

    JObject newsResponse = JObject.Parse(e.Result);
    IList<JToken> results = newsResponse["NewsResponse"]["NewsItems"]["NewsItem"].Children().ToList(); //Here don't see ToList()
    List<News> newsResults = new List<News>();
    
    foreach (JToken result in results)
    {
        News searchResult = JsonConvert.DeserializeObject<News>(result.ToString());
        newsResults.Add(searchResult);
    }
    

    Error:

    'Newtonsoft.Json.Linq.JEnumerable' does not contain a definition for 'ToList' and no extension method 'ToList' accepting a first argument of type 'Newtonsoft.Json.Linq.JEnumerable' could be found (are you missing a using directive or an assembly reference?)

  • jv42
    jv42 about 5 years
    var is quite different from an anonymous type, it's only a keyword telling the compiler to fill in the type for you, you're still using static typing and the type of the expression doesn't change (no conversion or anything).