我試圖從使用以下格式Json.NET,Web服務返回數據的Web服務解析JSON:Json.Net反序列化JSON與索引名對象
{
"0": {
"ID": 193,
"Title": "Title 193",
"Description": "Description 193",
"Order": 5,
"Hyperlink": "http://someurl.com"
},
"1": {
"ID": 228,
"Title": "Title 228",
"Description": "Description 228",
"Order": 4,
"Hyperlink": "http://someurl.com"
},
"2": {
"ID": 234,
"Title": "Title 234",
"Description": "Description 234",
"Order": 3,
"Hyperlink": "http://someurl.com"
}
}
我以前json2sharp生成從JSON類:
public class __invalid_type__0
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Order { get; set; }
public string Hyperlink { get; set; }
}
public class __invalid_type__1
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Order { get; set; }
public string Hyperlink { get; set; }
}
public class __invalid_type__2
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Order { get; set; }
public string Hyperlink { get; set; }
}
public class RootObject
{
public __invalid_type__0 __invalid_name__0 { get; set; }
public __invalid_type__1 __invalid_name__1 { get; set; }
public __invalid_type__2 __invalid_name__2 { get; set; }
}
我再清理類,並留下了以下內容:
public class Articles
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Order { get; set; }
public string Hyperlink { get; set; }
}
public class FeaturedArticles
{
public List<Articles> articles { get; set; }
}
當我嘗試將數據加載到我的單身人士使用的應用程序:
private void fetchFeaturedArticles()
{
var client = new RestClient (_featuredArticlesJsonUrl);
var request = new RestRequest (Method.GET);
var response = client.Execute (request);
_featuredArticles = JsonConvert.DeserializeObject<FeaturedArticles> (response.Content);
foreach (Articles a in _featuredArticles.Articles)
Console.WriteLine (a.Title);
}
我發現文章沒有得到反序列化。
我已驗證JSON數據是從Web服務返回的。我相信問題存在於我的JSON提要的結構中,其中從提要返回的每個項目被賦予一個名稱,該名稱等於該項目被返回的索引。
我是新來使用Json.NET,所以我不知道我應該如何繼續;我無法更改JSON Feed的結構,但需要使用它的數據。任何人有任何建議?
嘗試使用詞典<字符串,文章>而不是List –
Jason
@jason'詞典'似乎更合適 –
tvanfosson