c#从json

时间:2017-12-12 11:55:11

标签: c# json json.net

我有一个json文本,我想获取作者姓名和描述标签的值。不需要其他字段,如url和urltoimage等等。 当我运行以下代码时,不提供任何字符串值。我觉得有些错误在这里。

{
  "status": "ok",
  "articles": [
  {
    "source": {
      "id": "techcrunch",
      "name": "TechCrunch"
    },
    "author": "Khaled \"Tito\" Hamze",
    "title": "Crunch Report",
    "description": "Your daily roundup of the biggest TechCrunch stories and startup news.",
    "url": "https://techcrunch.com/video/crunchreport/",
    "urlToImage": "https://tctechcrunch2011.files.wordpress.com/2015/03/tccrshowogo.jpg?w=500&h=200&crop=1",
    "publishedAt": "2017-12-11T20:20:09Z"
  },
  {
    "source": {
      "id": "techcrunch",
      "name": "TechCrunch"
    },
    "author": "Sarah Perez",
    "title": "Facebook is trying to make the Poke happen again",
    "description": "Facebook's \"Poke\" feature has never really gone away, but now the social network is giving it a more prominent placement - and is even considering expanding..",
    "url": "https://techcrunch.com/2017/12/11/facebook-is-trying-to-make-the-poke-happen-again/",
    "urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/12/facebook-poke-icon.jpg",
    "publishedAt": "2017-12-11T20:02:30Z"
  },
  {
    "source": {
      "id": "techcrunch",
      "name": "TechCrunch"
    },
    "author": "Sarah Perez",
    "title": "Amazon Alexa can now wake you up to music",
    "description": "This fall, Amazon made a play to become your new alarm clock with the introduction of a combination smart speaker and clock called the Echo Spot. Today, the..",
    "url": "https://techcrunch.com/2017/12/11/amazon-alexa-can-now-wake-you-up-to-music/",
    "urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/09/amazon-event-9270069.jpg",
    "publishedAt": "2017-12-11T17:22:30Z"
  },
  {
    "source": {
      "id": "techcrunch",
      "name": "TechCrunch"
    },
    "author": "Ingrid Lunden, Katie Roof",
    "title": "Apple confirms Shazam acquisition; Snap and Spotify also expressed interest",
    "description": "After we broke the story last week that Apple was acquiring London-based music and image recognition service Shazam, Apple confirmed the news today. It is..",
    "url": "https://techcrunch.com/2017/12/11/apple-shazam-deal/",
    "urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/12/shazam-app-icon-ios.jpg",
    "publishedAt": "2017-12-11T15:59:31Z"
  }
]}

怎么弄这个?下面是我的代码,它根本没有工作

var data = (JObject)JsonConvert.DeserializeObject(myJSON);
string nameArticles= data["articles"].Value<string>();
MessageBox.Show(nameArticles);


   public class Source
   {
    public string id { get; set; }
    public string name { get; set; }
   }
   public class Article
   {
    public Source source { get; set; }
    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 DateTime publishedAt { get; set; }
   }

            Article art = new Article();

            art = JsonConvert.DeserializeObject<Article>(myJSON);

            MessageBox.Show(art.description.ToString());

上面的代码返回对象未设置为实例错误!

7 个答案:

答案 0 :(得分:1)

假设您希望反序列化为具体类(根据您的问题中显示的第二种尝试方法),那么您需要一个包装类来保存整个对象,并反序列化。目前,您正在尝试将整个对象序列化为文章,但只有该对象的“articles”数组中的单个对象才会与Article类中的结构匹配。您试图在对象的错误级别执行操作,并且您忘记了文章是列表(数组)这一事实。

这样的事情:

public class JSONResponse
{
    public string status { get; set; }
    public List<Article> articles { get; set; }
}

JSONResponse response = JsonConvert.DeserializeObject<JSONResponse>(myJSON);

然后,您可以使用普通循环遍历response.articles列表并提取作者姓名和说明。

答案 1 :(得分:1)

data["articles"]可能是JArray而不是字符串。您需要迭代上述JObject中的每个JArray,并提取作者和描述值

var data = (JObject)JsonConvert.DeserializeObject(myJSON);
var articles = data["articles"].Children();

foreach (var article in articles)
{
    var author = article["author"].Value<string>();
    var description = article["author"].Value<string>();

    Console.WriteLine($"Author: " + author + ", Description: " + description);
}

这可以帮助您开始使用您正在做的任何事情。

答案 2 :(得分:1)

如果您不想创建包装类,可以尝试下面的代码段。

            var json = "Your JSON string";

            dynamic stuff = JsonConvert.DeserializeObject(json);

            string name = stuff.status;
            var arr = stuff.articles;

            foreach (var a in arr)
            {
                var authorName = a.author;
            }

答案 3 :(得分:0)

你的Json在下面的课程

public class Source
{ 
  public string id { get; set; } 
  public string name{get;set;}
}
public class Article
{
public Source source { get; set; }
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 DateTime publishedAt { get; set; }
}

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

所以你通过以下方式反序列化..

var data = JsonConvert.DeserializeObject<RootObject>(myJSON);
nameArticles=data.articles.FirstOrDefault().description;
MessageBox.Show(nameArticles);

答案 4 :(得分:0)

样本json数据

string jsonString = "{\"displayName\":\"Alex Wu\",\"signInNames\":[{\"type\":\"emailAddress\",\"value\":\"AlexW@example.com\"},{\"type\":\"emailAddress\",\"value\":\"AlexW2@example.com\"}]}";

将json转换为jObject并使用名为selectToken()的内置方法获取值

JObject jObject = JObject.Parse(jsonString);
        string displayName = (string)jObject.SelectToken("displayName");
        string type = (string)jObject.SelectToken("signInNames[0].type");
        string value = (string)jObject.SelectToken("signInNames[0].value");
        Console.WriteLine("{0}, {1}, {2}", displayName, type, value);
        JArray signInNames = (JArray)jObject.SelectToken("signInNames");
        foreach (JToken signInName in signInNames)
        {
            type = (string)signInName.SelectToken("type");
            value = (string)signInName.SelectToken("value");
            Console.WriteLine("{0}, {1}",  type, value);
        }

谢谢

答案 5 :(得分:-1)

使用Json.NET

示例:

$url_vars

答案 6 :(得分:-1)

请为您的JSON文件创建一个类,并为所有标记添加属性 然后编写如下代码:

public class exampleJson{
public string author {get;set;}
public string description {get;set;}
.....

}

var data = JsonConvert.DeserializeObject<exampleJson>(myJSON);
string authorName = data.author;
string descriptions = data.description ;