从嵌套的JSON - system . collections . general . list ' 1[System.String]中检索字符串

时间:2021-07-02 14:29:39

I am using a JSON Object to get news titles from various websites. When I unpack it I can access one title but when i try to loop over the items and add them to a list to get all titles I get the following error:

我正在使用JSON对象从各种网站获取新闻标题。当我解压它时,我可以访问一个标题,但当我试图循环项目,并将它们添加到一个列表,以获得所有标题时,我得到以下错误:

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

“System.Collections.Generic.List.Add(string)”的最佳重载方法匹配有一些无效的参数

I am using newtonsoft.json and then make it into a dynamic object in order to get access through dot notation.

我用newtonsoft。然后将它变成一个动态对象,以便通过点表示法进行访问。

JSON Example

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"
    }]
}

code:

代码:

// 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;

1 个解决方案

#1


1  

Newtonsoft will actually provide you JValue items when you're deserializing into an object or dynamic type.

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

So, this line here:

所以,这条线:

var articleTitle = article.title;

articleType is of type JValue, not string. Thus, when you call List<string>.Add(articleType) - it fails, as there's no overload accepting a JValue.

articleType是JValue类型,不是string类型。因此,当您调用List . add (articleType)时,它会失败,因为没有重载接受JValue。

Luckily, JValue has overloaded cast operators which allow you to unwrap the actual value. Simply changing the above line to:

幸运的是,JValue已经重载了cast操作符,允许您展开实际的值。简单地将上面的行改为:

string articleTitle = article.title;

Is enough to get your code to work.

足以让代码工作。

#1


1  

Newtonsoft will actually provide you JValue items when you're deserializing into an object or dynamic type.

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

So, this line here:

所以,这条线:

var articleTitle = article.title;

articleType is of type JValue, not string. Thus, when you call List<string>.Add(articleType) - it fails, as there's no overload accepting a JValue.

articleType是JValue类型,不是string类型。因此,当您调用List . add (articleType)时,它会失败,因为没有重载接受JValue。

Luckily, JValue has overloaded cast operators which allow you to unwrap the actual value. Simply changing the above line to:

幸运的是,JValue已经重载了cast操作符,允许您展开实际的值。简单地将上面的行改为:

string articleTitle = article.title;

Is enough to get your code to work.

足以让代码工作。