2011-05-11 25 views
0

我從nyTimes獲取json字符串「jasonContent」。當我寫了下面的代碼,我可以得到的總價值和偏移,但我感興趣的結果,但我得到什麼了,我接受results.The字符串是這樣的在C#中解析Json字符串時不創建值#

{ 

    "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); 

回答

1

問題解決了。 (我正在使用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;