c# - 获取动态 JSON 值并打印出来
问题描述
我从 API 中获取 JSON,像 Google 和 Facebook 这样的每个域都是动态的。我正在努力访问 JSON 然后放到网页上,通常 API 没有问题,但事实上它的动态导致了问题。此外,StackOverflow 上的任何解决方案都无法解决我的问题。我已经尝试过这个解决方案,但不幸的是,它没有用。
所以一个示例响应
{
"data": {
"google.com": {
"domain_authority": 95,
"page_authority": 88,
"spam_score": 1,
"nofollow_links": 76221395,
"dofollow_links": 465226564
},
"facebook.com": {
"domain_authority": 96,
"page_authority": 100,
"spam_score": 1,
"nofollow_links": 97570534,
"dofollow_links": 565869181
},
"wikipedia.org": {
"domain_authority": 90,
"page_authority": 75,
"spam_score": 1,
"nofollow_links": 1897582,
"dofollow_links": 20437023
}
}
}
我从示例响应中获取 Google 价值的代码:
IRestResponse response = client.Execute(request);
// response.Content returns the JSON
var w = new JavaScriptSerializer().Deserialize<Rootobject>(response.Content);
//trying to echo out Google's Domain Authority.
Response.Write(w.data[0].domain_authority);
public class Rootobject
{
public Data data { get; set; }
}
public class Data
{
public int domain_authority { get; set; }
public int page_authority { get; set; }
public int spam_score { get; set; }
public int nofollow_links { get; set; }
public int dofollow_links { get; set; }
}
最新尝试(虽然我无法通过 JSON 获取域名):
IRestResponse response = client.Execute(request);
var root = JsonConvert.DeserializeObject<Rootobject>(response.Content);
var json2 = JsonConvert.SerializeObject(root, Newtonsoft.Json.Formatting.Indented);
var list = root.data.Values;
int c = 1;
foreach (var domains in list)
{
Response.Write(" "+c+":" + domains.domain_authority);
c++;
}
public class Rootobject
{
public Dictionary<string, Data> data { get; set; }
}
public class Data
{
public int domain_authority { get; set; }
public int page_authority { get; set; }
public int spam_score { get; set; }
public int nofollow_links { get; set; }
public int dofollow_links { get; set; }
}
以下两项工作都没有——而且我觉得我很傻(对 C# 来说相对较新,如果很明显很抱歉)。
解决方案
除非您特别想要一个对象,否则将其保留为 JsonDocument 可能是一种更简单、更灵活的解决方案。
//using System.Text.Json;
JsonDocument document = JsonDocument.Parse(@"{ ""data"" : { ""google.com"" : { ""domain_authority"" : 95 } , ""facebook.com"" : { ""domain_authority"" : 76 } } }");
JsonElement root = document.RootElement;
JsonElement data = root.GetProperty("data");
foreach (var domain in data.EnumerateObject())
{
Console.WriteLine($"got domain {domain.Name}, auth {domain.Value.GetProperty("domain_authority")}");
}
创建输出:
got domain google.com, auth 95
got domain facebook.com, auth 76
推荐阅读
- python - 将数组的 Python 字典转换为数据框
- sql - 选择计数内连接两个数据库
- android - 滚动和缩放Textview之间的冲突
- angular6 - Angular 6 HttpClient.get Observable 不赋值
- ruby-on-rails - Geocoder Nearby 方法
- java - Dockerize java项目
- javascript - 如何使用不同的方式过滤两个图表以使用相同的字符串过滤器获取数据?
- ruby-on-rails - 将范围添加到 ActiveAdmin 路由获取 ActionController::UrlGenerationError
- python-3.x - 无法在使用 gethostname ping 时捕获主机名
- azure - 是否可以将现有的 IaaS VM 操作系统映像从 2012 升级到 2016