I'm trying to deserialize a JSON object retrieved from Web API into list of strong type objects as follows:
WebClient wc = new WebClient();
// Downloading & Deserializing the Json file
var jsonMain = wc.DownloadString("http://api.flexianalysis.com/services/FlexiAnalysisService.svc/FlexiAnalysisNews?key=___&catagory=Forex");
JObject token2 = JObject.Parse(jsonMain);
List<News> listNews = new List<News>();
foreach (var result in token2["d"])
{
news = new News();
news.id = (string)result["ID"];
news.Title = (string)result["Title"];
news.Date = (string)result["PublishingDate"];
news.Content = (string)result["News"];
listNews.Add(news);
}
return View(listNews);
The problem is that I always get the result as one string, Because the parser does not parse a valid JSON object. (I guess it get's to invalid character and can't get it parsed correctly)...
Does anyone have any ideas?
You need to JArray results = JArray.Parse(token2["d"].ToString());
Please try
WebClient wc = new WebClient();
// Downloading & Deserializing the Json file
var jsonMain = wc.DownloadString("http://api.flexianalysis.com/services/FlexiAnalysisService.svc/FlexiAnalysisNews?key=gZ_lhbJ_46ThmvEki2lF&catagory=Forex");
JObject token2 = JObject.Parse(jsonMain);
JArray results = JArray.Parse(token2["d"].ToString());
List<News> listNews = new List<News>();
foreach (var result in results)
{
news = new News();
news.id = (string)result["ID"];
news.Title = (string)result["Title"];
news.Date = (string)result["PublishingDate"];
news.Content = (string)result["News"];
listNews.Add(news);
}
return View(listNews);
Test: