问题
I'm trying to deserialize A Json object retrived 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 1 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?
回答1:
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:
回答2:
You can also try to use a Dictionary<string, IEnumerable<Dictionary<string, object>>>:
var root = JsonConvert.DeserializeObject<Dictionary<string, IEnumerable<Dictionary<string, object>>>>(jsonMain);
List<News> news = root["d"].Select(result => new News()
{
id = result["ID"] as string,
Title = result["Title"] as string,
Date = result["PublishingDate"] as string,
Content = result["News"] as string
}).ToList();
return View(news);
回答3:
can be alternative
class News
{
[JsonProperty("ID")]
public int id { get; set; }
[JsonProperty("Title")]
public string Title { get; set; }
[JsonProperty("PublishingDate")]
public DateTime Date { get; set; }
[JsonProperty("News")]
public string Content { get; set; }
}
WebClient implements IDisposible interface. Using it in a using statement is not bad.
using (WebClient wc = new WebClient())
{
var jsonMain = wc.DownloadString("http://api.flexianalysis.com/services/FlexiAnalysisService.svc/FlexiAnalysisNews?key=gZ_lhbJ_46ThmvEki2lF&catagory=Forex");
JObject token2 = JObject.Parse(jsonMain);
string s = token2["d"].ToString();
List<News> list = JArray.Parse(s).ToObject<List<News>>();
}
来源:https://stackoverflow.com/questions/42649558/json-deserialization-parsing-non-valid-json-object