NewsAPI를 사용하여 관련 기사를 얻으려고하는데 반환 유형은 JSON 객체입니다. 나는 전에 JSON 객체로 작업 한 적이 없으며 내가 찾은 모든 답변은 각 특정 JSON 객체에 대해 개인화 된 것처럼 보이지만 실제로 적용하는 방법을 이해할 수 없었습니다.
C #의 다음 코드 ...
using System.Net;
var url = "https://newsapi.org/v2/top-headlines?" +
"country=us&" +
"apiKey=*mySpecificKey*";
var json = new WebClient().DownloadString(url);
다음과 같은 JSON 객체를 제공합니다 ...
{
"status": "ok",
"totalResults": 38,
-
"articles": [
-
{
-
"source": {
"id": "cnn",
"name": "CNN"
},
"author": "Frederik Pleitgen and Mary Ilyushina, CNN",
"title": "US is out of the picture in Syria-Turkey crisis. Putin now owns this mess - CNN",
"description": "As US President Donald Trump hailed the agreement his administration negotiated with the Turks for northern Syria as \"a great day for civilization,\" the Turks quickly dumped cold water over the White House's euphoria, refusing to even call the deal a ceasefir…",
"url": "https://www.cnn.com/2019/10/20/middleeast/putin-now-owns-this-mess-intl/index.html",
"urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/190827100831-russia-turkey-aviation-politics-diplomacy-super-tease.jpg",
"publishedAt": "2019-10-20T05:16:00Z",
"content": "Moscow (CNN)As US President Donald Trump hailed the agreement his administration negotiated with the Turks for northern Syria as \"a great day for civilization,\" the Turks quickly dumped cold water over the White House's euphoria, refusing to even call the dea… [+6294 chars]"
},
-
{
-
"source": {
"id": null,
"name": "Bbc.com"
... and so on.
그리고 각 기사의 URL에 액세스해야합니다. JSON 객체의 초보 사용자로서 각 기사에서 URL을 가져 오는 방법은 무엇입니까? 가능한 한 자세히 설명해주십시오. 도움을 주셔서 미리 감사드립니다 !!
이를 위해 잘 알려진 lib Newtonsoft.Json을 사용해야합니다. 여기에서는 3 개의 클래스를 통해 JSON 결과의 전체 모델을 생성합니다. 메인 클래스는 기사와 소스를 포함하는 Result.json입니다. 그리고 json을 요청하고 얻은 후해야 할 일은 역 직렬화해야합니다. 그리고 LINQ를 통해 모든 URL을 얻습니다.
이 코드를보세요. 나는 이미 테스트했으며 작동합니다.
public class Source
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
}
public class Article
{
[JsonProperty(PropertyName = "author")]
public string Author { get; set; }
[JsonProperty(PropertyName = "title")]
public string Title { get; set; }
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
[JsonProperty(PropertyName = "url")]
public string Url { get; set; }
[JsonProperty(PropertyName = "urlToImage")]
public string UtlToImage { get; set; }
[JsonProperty(PropertyName = "publishedAt")]
public string PublishedAt { get; set; }
[JsonProperty(PropertyName = "content")]
public string Content { get;set; }
}
public class ResultJson
{
public List<Source> Sources { get; set; }
public List<Article> Articles { get; set; }
}
public class Programm
{
var json = new WebClient().DownloadString(url);
var articles = JsonConvert.DeserializeObject<ResultJson>(json).Articles.ToList();
List<string> allUrls = new List<string>();
allUrls = articles.Select(u => u.Url).ToList();
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다