Search code examples
c#deserializationwikipedia-apijson-deserialization

Get all the titles after deserialiaztion json using C# and Json.net


I am using a wikipedia api which contains external links of all places from a wikipedia article. My wikipedia api call is: https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gspage=Berlin&gslimit=500&gsprop=type|name|dim|country|region|globe&format=json

I make c# classes for json object using JsonToCsharp as follows:

  public class Geosearch
  {
    public int pageid { get; set; }
    public int ns { get; set; }
    public string title { get; set; }
    public double lat { get; set; }
    public double lon { get; set; }
    public double dist { get; set; }
    public string primary { get; set; }
    public string type { get; set; }
    public string name { get; set; }
    public object dim { get; set; }
    public string country { get; set; }
    public string region { get; set; }
  }

 public class Query
 {
   public List<Geosearch> geosearch { get; set; }
 }  

 public class RootObject
 {
  public string batchcomplete { get; set; }
  public Query query { get; set; }
 }

My deserialization code is as follows.With this code I got only one Title. But I want to get all the title from this api. I know I should make a foreach loop, but could not get logic how to implement it.

static void Main(string[] args)
    {
        WebClient client = new WebClient();
        var GeoResponse = client.DownloadString("https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gspage=Berlin&gslimit=500&gsprop=type|name|dim|country|region|globe&format=json");

        RootObject json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<RootObject>(GeoResponse);

        var firstKey = json.query.geosearch.First().title;

        Console.WriteLine(firstKey);

    }

Solution

  • This works fine -

    var o = new HttpClient();
    var res = new StreamReader(o.GetStreamAsync("https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gspage=Berlin&gslimit=500&gsprop=type|name|dim|country|region|globe&format=json").Result).ReadToEnd() ;
    var obj = JsonConvert.DeserializeObject<RootObject>(res).query.geosearch.Select(a => a.title).ToList();
    // count == 500
    obj.Foreach(a => Console.WriteLine(a));