Json反序列化解析无效的Json对象

问题描述 投票:0回答:3

我正在尝试将从 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);

问题是我总是得到一个字符串形式的结果,因为解析器不解析有效的 JSON 对象。 (我猜它是无效字符并且无法正确解析)...

有人有什么想法吗?

c# json .net deserialization webapi
3个回答
0
投票

你需要

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

测试:

enter image description here


0
投票

您也可以尝试使用

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

0
投票

可以替代

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 语句中使用它也不错。

        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>>();
        }
© www.soinside.com 2019 - 2024. All rights reserved.