简体   繁体   中英

Using C# and Json.Net for parsing

An API is returning to me the following json:

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

I used json2csharp to build a class representing this json (I manually tweaked the names for PageInfo, as it was coughing on this name and calling 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 examine and see root.query.pages all have values, but pageInfo is null. I'm not sure what I'm missing that will allow me to load this json into an object.

Change your class definiton as below. it will work.. (see the definition of Query class)

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM