首页 > 解决方案 > 创建一个从 API url 读取/显示 JSON 数据的琐事应用程序

问题描述

每当我运行这个程序时,JSON 可视化器都会显示所有 JSON 都是从 url 读取的,但是它一直说在反序列化对象后发现了额外的文本。

我的主要目标是能够读取 JSON 并将其添加到某种数据集中,以便我可以显示它

    public class Wrapper
    {
        [JsonProperty("results")]

        public DataSet DataSet { get; set; }
    }
    public class Rootobject
    {
        public int response_code { get; set; }
        public Result[] results { get; set; }
    }

    public class Result
    {
        public string category { get; set; }
        public string type { get; set; }
        public string difficulty { get; set; }
        public string question { get; set; }
        public string correct_answer { get; set; }
        public string[] incorrect_answers { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {



            string json = (new WebClient()).DownloadString("https://opentdb.com/api.php?amount=10&type=boolean");
            DataSet ds = JsonConvert.DeserializeObject<Wrapper>(json).DataSet;

        }
    }
}

}

标签: c#jsonapiurl

解决方案


试试这个(仍在更新):

ToDataSet从这里得到了

static class MyDSet
{
    public static DataSet ToMyDataSet<T>(this IList<T> list)
    {
        Type elementType = typeof(T);
        DataSet ds = new DataSet();
        DataTable t = new DataTable();
        ds.Tables.Add(t);

        //add a column to table for each public property on T
        foreach (var propInfo in elementType.GetProperties())
        {
            t.Columns.Add(propInfo.Name, propInfo.PropertyType);
        }

        //go through each property on T and add each value to the table
        foreach (T item in list)
        {
            DataRow row = t.NewRow();
            foreach (var propInfo in elementType.GetProperties())
            {
                row[propInfo.Name] = propInfo.GetValue(item, null);
            }
        }

        return ds;
    }
}

public class Wrapper
{
    [JsonProperty("results")]

    public DataSet DataSet { get; set; }
}

public class Result
{
    public string category { get; set; }
    public string type { get; set; }
    public string difficulty { get; set; }
    public string question { get; set; }
    public string correct_answer { get; set; }
    public List<string> incorrect_answers { get; set; }
}

public class RootObject
{
    public int response_code { get; set; }
    public List<Result> results { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string json = (new WebClient()).DownloadString("https://opentdb.com/api.php?amount=10&type=boolean");
        var ds = JsonConvert.DeserializeObject<RootObject>(json);
        Wrapper wrapper = new Wrapper();
        wrapper.DataSet = ds.results.ToMyDataSet();
        Console.WriteLine(ds.response_code);
        Console.WriteLine("Hello World!");
        Console.ReadKey();
    }
}

最后,我反序列化了 Root 对象,然后将根对象中的结果列表转换为数据集。可能有一种简化的方法来编写反序列化对象、转换和分配的语法。


推荐阅读