我从一个API获取JSON,每个域都像Google,而Facebook将是动态的。我正在努力访问JSON,然后放到一个网页上,通常API是没有问题的,但它的动态造成了问题。此外,在StackOverflow上没有任何解决方案可以解决我的问题。我已经尝试过this solution,但不幸的是,它不起作用。
所以下面是一个示例响应
{
"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#来说,这是相对较新的,如果很明显的话,很抱歉)。
发布于 2020-04-17 07:21:04
除非您特别想要一个对象,否则将其保留为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 76https://stackoverflow.com/questions/61261643
复制相似问题