【发布时间】:2020-04-16 23:15:26
【问题描述】:
我从 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# 来说相对较新,如果很明显很抱歉)。
【问题讨论】:
-
使用字典:
public Dictionary<string, Data> data { get; set; },如How can I parse a JSON string that would cause illegal C# identifiers?或Deserializing JSON when key values are unknown或Deserializing JSON with unknown object names或Parsing JSON Object with variable properties into strongly typed object所示。 -
另外,
JavaScriptSerializer已弃用,请考虑升级到 json.net 或 system.text.json。 -
@dbc,感谢您的建议。我试了一下
var w = JsonConvert.DeserializeObject<Dictionary<string, Data>>(response.Content);,虽然没有摔倒,但根本没有返回任何值。 -
您需要将字典设为根对象的属性:
public class Rootobject { public Dictionary<string, Data> data { get; set; } }。然后像现在一样反序列化根对象。演示小提琴:dotnetfiddle.net/oFgVH2 -
仍然无法正常工作,这就是我所看到的:gyazo.com/c0e125cd8f8df24e118ac63ec7eb16b3