Using C # and Json.Net for Parsing

The API returns me the following json:

{
   "query":{
      "pages":{
         "49123":{
            "pageid":49123,
            "ns":0,
            "title":"Phoenix (constellation)",
            "revisions":[
               {
                  "revid":588710862,
                  "parentid":588710834
               }
            ]
         }
      }
   }
}

I used json2csharp to create a class representing this json (I manually changed the names for PageInfo since it coughed to that name and calls it __ invalid_type__49123 )

public class Revision
{
    public int revid { get; set; }
    public int parentid { get; set; }
}

public class PageInfo
{
    public int pageid { get; set; }
    public int ns { get; set; }
    public string title { get; set; }
    public List<Revision> revisions { get; set; }
}

public class Pages
{
    public PageInfo pageInfo { get; set; }
}

public class Query
{
    public Pages pages { get; set; }
}

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

and tried to parse it:

        var json = "{\"query\":{\"pages\":{\"49123\":{\"pageid\":49123,\"ns\":0,\"title\":\"Phoenix (constellation)\",\"revisions\":[{\"revid\":588710862,\"parentid\":588710834}]}}}}";
        // unescaped version of json below
        // {"query":{"pages":{"49123":{"pageid":49123,"ns":0,"title":"Phoenix (constellation)","revisions":[{"revid":588710862,"parentid":588710834}]}}}}

        var root = JsonConvert.DeserializeObject<RootObject>(json);

I can check and see that root.query.pages are relevant, but pageInfo is null. I'm not sure what I am missing, which will allow me to load this json into an object.

+4
source share
1 answer

Change your class definition as shown below. it will work .. (see class definition Query)

public class Revision
{
    public int revid { get; set; }
    public int parentid { get; set; }
}

public class Page
{
    public int pageid { get; set; }
    public int ns { get; set; }
    public string title { get; set; }
    public List<Revision> revisions { get; set; }
}

public class Query
{
    public Dictionary<string,Page>  pages { get; set; }
}

public class RootObject
{
    public Query query { get; set; }
}
+6
source

All Articles