c# - 创建一个从 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;
}
}
}
}
解决方案
试试这个(仍在更新):
我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 对象,然后将根对象中的结果列表转换为数据集。可能有一种简化的方法来编写反序列化对象、转换和分配的语法。
推荐阅读
- html - 修复表头并使表体滚动
- javascript - 将计算项定位在 flexbox 元素下方
- python - 如何从字典值字符串中动态删除引号
- jquery - AJAX成功的jQuery更新变量
- angular - 如何在打字稿或angular4+中从当前日期计算旧日期
- amazon-web-services - 我们能否通过 AWS Cloudformation 动态创建密钥对并将 .PEM 文件复制到 EC2 Linux 实例
- javascript - 当安装的节点 js 版本较高且应用程序使用旧版本时,如何运行节点 js 应用程序
- google-cloud-platform - Firestore 数据存储中发生冲突时,事务行为是否发生了变化?
- php - codeigniter - 在多维数组中获取所有相同的最小值或最大值
- python - Python Regex 使用变量编译