gpt4 book ai didi

c# - 从嵌套的 JSON 中检索字符串 - System.Collections.Generic.List`1[System.String]

转载 作者:太空宇宙 更新时间:2023-11-03 12:19:55 24 4
gpt4 key购买 nike

我正在使用 JSON 对象从各种网站获取新闻标题。当我打开它时,我可以访问一个标题,但是当我尝试遍历这些项目并将它们添加到列表中以获取所有标题时,我收到以下错误:

The best overloaded method match for 'System.Collections.Generic.List.Add(string)' has some invalid arguments

我正在使用 newtonsoft.json,然后将其变成一个动态对象,以便通过点符号进行访问。

JSON 示例

{
"status": "ok",
"totalResults": 10,
"articles": [{
"source": {
"id": "bloomberg",
"name": "Bloomberg"
},
"author": null,
"title": "Here’s Where the GOP Tax Plan Stands Right Now",
"description": "The House is scheduled to vote Tuesday on the tax bill and Senate leaders intend to bring the measure up as soon as they get it.",
"url": "http://www.bloomberg.com/news/articles/2017-12-19/house-plans-early-vote-democrats-plan-drama-tax-debate-update",
"urlToImage": "https://assets.bwbx.io/images/users/iqjWHBFdfxIU/isN9fqUqLwpE/v0/1200x800.jpg",
"publishedAt": "2017-12-19T09:00:00Z"
}, {
"source": {
"id": "bloomberg",
"name": "Bloomberg"
},
"author": "Dana Hull, Sarah Frier",
"title": "Elon Musk Appears to Have Misfired Direct Message to Oculus CTO",
"description": "Elon Musk appears to have just given his 16.7 million Twitter followers what he meant to send to the co-founder of the virtual-reality company Oculus: his phone number.",
"url": "http://www.bloomberg.com/news/articles/2017-12-19/elon-musk-appears-to-have-misfired-direct-message-to-oculus-cto",
"urlToImage": "https://assets.bwbx.io/images/users/iqjWHBFdfxIU/iqJHjveOq1j8/v1/1200x740.jpg",
"publishedAt": "2017-12-19T21:41:36Z"
}]
}

代码:

// Set base Website
var url = "https://newsapi.org/v2/top-headlines?sources=";
// Initiate Client
System.Net.WebClient client = new System.Net.WebClient();
// Get JSON Data
var json = client.DownloadString(url + site + apiKey);
// Convert to dynamic object
dynamic jOutput = JsonConvert.DeserializeObject(json);
// Get Articles
var articles = jOutput.articles;
//Declare List
List<String> titles = new List<String>();
foreach (var article in articles)
{
var articleTitle = article.title;
titles.Add(articleTitle);
}

string title = jOutput.articles[0].title;
//string txt = items[0].title;

最佳答案

Newtonsoft将为您实际提供JValue反序列化为对象或动态类型时的项目。

所以,这里的这一行:

var articleTitle = article.title;

articleType类型为 JValue , 不是 string .因此,当您调用 List<string>.Add(articleType) - 它失败了,因为没有接受 JValue 的过载.

幸运的是,JValue具有重载的强制转换运算符,可让您解包实际值。只需将上面的行更改为:

string articleTitle = article.title;

足以让您的代码正常工作。

关于c# - 从嵌套的 JSON 中检索字符串 - System.Collections.Generic.List`1[System.String],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47897343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com