如何使用Newtonsoft.Json(a.k.a Json.Net)从URL中创建JSON对象?

时间:2016-12-14 01:25:10

标签: c# json wpf json.net

我一直试图这样做一段时间没有好结果。我的obj.title调用似乎返回一个空字符串。

到目前为止,我有:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Test2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            using (WebClient wc = new WebClient())
            {
                var json = wc.DownloadString("https://newsapi.org/v1/articles?source=business-insider&sortBy=top&apiKey=f47672429b7044a29e7a4671f9f41c28");
                var obj = JsonConvert.DeserializeObject<MyClass>(json);
                label.Content = obj.title;
            }
        }
    }

    public class MyClass
    {
        public string title { get; set; }
    }
}

我使用的网址是https://newsapi.org/v1/articles?source=business-insider&sortBy=top&apiKey=f47672429b7044a29e7a4671f9f41c28

4 个答案:

答案 0 :(得分:1)

因此,您的JSON源返回一个如下所示的对象:

{
    "status": "ok",
    "source": "business-insider",
    "sortBy": "top",
    "articles": [{
        "author": "Allan Smith",
        "title": "Ethics experts say Trump's latest move to distance himself from his business empire is not enough: 'Nothing of consequence has changed'",
        "description": "Trump says he'll make \"no new deals\" and will pass control of his business empire off to his two adult sons and executives once he assumes office.",
        "url": "http://www.businessinsider.com/trump-conflicts-of-interest-latest-move-2016-12",
        "urlToImage": "http://static2.businessinsider.com/image/584f0536a1a45e1a008b53ba-1190-625/ethics-experts-say-trumps-latest-move-to-distance-himself-from-his-business-empire-is-not-enough-nothing-of-consequence-has-changed.jpg",
        "publishedAt": "2016-12-13T22:55:20Z"
    }, {
        "author": "Pamela Engel",
        "title": "'All anyone ever wanted was to be treated no better than animals': Syrians lose hope as Aleppo falls",
        "description": "The Syrian city of Aleppo has mostly fallen to regime forces, leaving many who oppose the brutal rule of President Bashar al-Assad feeling hopeless.",
        "url": "http://www.businessinsider.com/aleppo-siege-assad-syria-2016-12",
        "urlToImage": "http://static2.businessinsider.com/image/58508de0ca7f0cc2178b4e05-1190-625/all-anyone-ever-wanted-was-to-be-treated-no-better-than-animals-syrians-lose-hope-as-aleppo-falls.jpg",
        "publishedAt": "2016-12-13T23:34:31Z"
    }] //trimmed due to repetitiveness
}

JSON对象没有属性title。它有一个articles 数组,其中每个 都有title

你需要看起来像这样的课程:

public class SomeArticles
{
    public List<Article> Articles{get;set;}
}

public class Article
{
    public string Title{get;set;}
}

然后你会

var someArticles = JsonConvert.DeserializeObject<SomeArticles>(json);

然后

var firstArticleTitle = someArticles.Articles.First().Title;

答案 1 :(得分:0)

您反序列化的类应该是

public class MyClass
{
    public Article[] articles { get; set; }
}


public class Article
{
    public string title { get; set; }
}

答案 2 :(得分:0)

从JSON结构看,根对象看起来没有标题变量。有一系列文章,每个都有自己的标题。

答案 3 :(得分:0)

您可以这样做:

void Main()
{
    using (WebClient wc = new WebClient())
    {
        var json = wc.DownloadString("https://newsapi.org/v1/articles?source=business-insider&sortBy=top&apiKey=f47672429b7044a29e7a4671f9f41c28");
        var obj = JsonConvert.DeserializeObject<RootObject>(json);
        Console.WriteLine(obj.articles[0].title);
    }
}


    public class Article
{
    public string author { get; set; }
    public string title { get; set; }
    public string description { get; set; }
    public string url { get; set; }
    public string urlToImage { get; set; }
    public string publishedAt { get; set; }
}

public class RootObject
{
    public string status { get; set; }
    public string source { get; set; }
    public string sortBy { get; set; }
    public List<Article> articles { get; set; }
}

此致