Json反序列化解析无效的Json对象
Posted
技术标签:
【中文标题】Json反序列化解析无效的Json对象【英文标题】:Json Deserialization parsing non valid Json object 【发布时间】:2017-07-27 17:39:14 【问题描述】:我正在尝试将从 Web API 检索到的 Json 对象反序列化为强类型对象列表,如下所示:
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);
问题是我总是得到 1 个字符串的结果,因为解析器没有解析一个有效的 Json 对象。 (我猜它是无效字符,无法正确解析)...
有人有什么想法吗?
【问题讨论】:
那么你想要一个 JSON 解析器来解析非 JSON 吗?d
的内容是一个有效的 JSON。我刚刚在jsonviewer.stack.hu 中将其可视化
【参考方案1】:
你需要JArray results = JArray.Parse(token2["d"].ToString());
请尝试
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);
测试:
【讨论】:
【参考方案2】:您也可以尝试使用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);
【讨论】:
这行不通。您收到“附加信息:转换值时出错...”i.imgur.com/VwqrXlQ.png【参考方案3】:可以选择
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 实现了 IDisposible 接口。在using statement 中使用它还不错。
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>>();
【讨论】:
以上是关于Json反序列化解析无效的Json对象的主要内容,如果未能解决你的问题,请参考以下文章
JSON PHP中,Json字符串反序列化成对象/数组的方法