在 C# 中解析 Json 字符串时未获取值



我从nyTimes获取json字符串"jasonContent"。当我编写以下代码时,我可以获取总计和偏移量的值,但我对结果感兴趣,但我对结果一无所获。我收到的字符串是这样的

{
  "offset": "0",
   "results": [
    {
      "body": " news goes here",
      "byline": "By SANA SIWOLOP",
      "date": "20110511",
      "title": "SQUARE FEET; Chelsea Piers, a Manhattan Sports Center, Expands Close to Home",
      "url": "http://www.nytimes.com/2011/05/11/realestate/commercial/chelsea-piers-a-manhattan-sports-center-expands-close-to-home.html"
    },
    {
      "body": "news 2 goes here",
      "byline": "By ROB HUGHES",
      "date": "20110511",
      "title": "ON SOCCER; Racial Politics Rear Their Head in French Soccer",
      "url": "http://www.nytimes.com/2011/05/11/sports/soccer/11iht-SOCCER11.html"
    },
    {
      "body": "news3 does here",
      "byline": "By RICHARD SANDOMIR",
      "date": "20110511",
      "title": "Gus Johnson Joins Fox Sports",
      "url": "http://www.nytimes.com/2011/05/11/sports/gus-johnson-joins-fox-sports.html"
    },],"tokens": [
 "sports" ],
  "total": 152539
}

为了解析这个字符串,我正在编写以下代码

 public class nytimesnews
{
    public string offset { get; set; }
    public resultobject news2;
    public string total { get; set; }
}
public class resultobject
{
    public results[] news;
}
public class results
{
    public string body { get; set; }
    public string byline { get; set; }
    public string date { get; set; }
    public string title { get; set; }
    public string url { get; set; }
}

nytimesnews parse = JsonConvert.DeserializeObject<nytimesnews>(jasonContent);

问题解决了。(我正在使用 Json.NET)。我注意到nytimesnews类的变量应该根据json字符串命名。我对代码进行了以下更改,它运行良好。

 public class nytimesnews
 {
       // name of these variables are just like the  data tags in json string
       public string offset { get; set; }      
       public result[] results;
       public string total { get; set; }
 }
 public class results
 {
       public string body { get; set; }
       public string byline { get; set; }
       public string date { get; set; }
       public string title { get; set; }
       public string url { get; set; }
 }

然后在我的主类中,我只使用了以下代码

 // jasonContent is the jason string
 nytimesnews parse = JsonConvert.DeserializeObject<nytimesnews>(jasonContent);
 jasonContent = parse.results[1].body;

相关内容

  • 没有找到相关文章

最新更新