-->

Json deserialize from wikipedia api with c#

2020-07-30 02:53发布

问题:

I have a wikipedia api with json format. Now I want to get the extract information from this api. I want to make it dynamic for any wikipedia api. [My wikipedia api][1]. I got following information from jsontoCsharp

namespace Json_deserialize
 {
   public class pageval
  {
    public int pageid { get; set; }
    public int ns { get; set; }
    public string title { get; set; }
    public string extract { get; set; }
}


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

public class Limits
{
    public int extracts { get; set; }
}

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

class Short_text
  {
    public static RichTextBox txt1 = new RichTextBox();
    public static void shortText()
    {
        using (WebClient wc = new WebClient())
        {
            var client = new WebClient();
            var response = client.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=Neuschwanstein%20Castle&redirects="); ;

            pageval m = JsonConvert.DeserializeObject<pageval>(response);

            string result = m.extract;

            txt1.Text = result;
         }

      }

  }

}

I want to make such a coding which should be dynamic. That means the id 240912 should be varied in time. I tried a lot. but cannot get a satisfied result.

回答1:

All JSON objects are essentially dictionaries. However, it usually makes sense to represent them as classes in C#, assuming the schema is constant. For cases where property names are not always the same, it's impossible to write a class to represent the object; so you much use dynamic or a dictionary

public class pageval
{
    public int pageid { get; set; }
    public int ns { get; set; }
    public string title { get; set; }
    public string extract { get; set; }
}


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

public class Limits
{
    public int extracts { get; set; }
}

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

To get the extract:

var response = client.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=Neuschwanstein%20Castle&redirects="); ;

var responseJson = JsonConvert.DeserializeObject<RootObject>(response);
var firstKey = responseJson.query.pages.First().Key;
var extract = responseJson.query.pages[firstKey].extract;