因此,基本上我想将JSON数据从特定URL反序列化到这个类结构,然后使用它在页面上显示它。
我不明白应该如何反序列化它,因为有两个类与url上的JSON结构兼容。
这是下面显示的代码。
public class IndexModel : PageModel
{
public void OnGet()
{
Rootobject rootobject = new Rootobject();
rootobject.regions[0] = _download_serialized_json_data<Region>("https://visservice.meteoalarm.org/api/v1/regions?language=ATOM");
}
private static Region _download_serialized_json_data<Region>(string url) where Region : new()
{
using (var w = new WebClient())
{
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<Region>(json_data) : new Region();
}
}
public class Rootobject
{
public Region[] regions { get; set; }
}
public class Region
{
public bool active { get; set; }
public float[][] bb { get; set; }
public string code { get; set; }
public string name { get; set; }
}
}
编辑:
json_data的值:
1条答案
按热度按时间wbgh16ku1#
根据类定义,它应该是
JsonConvert.DeserializeObject<Rootobject>(json_data)