控制台显示格式正确的JSON,但JsonObject无法解析它

问题描述:

我连接到外部API,(给定参数),以JSON打印结果集。目标是将此JSON转换为可读值并将它们添加到对象数组中。这是一款UWP应用程序,因此我在互联网上找到的一些较旧的库不再可用。以下是获取JSON并尝试解析它的代码块:控制台显示格式正确的JSON,但JsonObject无法解析它

private void beginWork() 
{ 
    string feed_data = getFeed().Replace(@"\", "").Trim(new char[1] { '"' }); 
    Debug.WriteLine(feed_data); // <-- THIS PRINTS OUT THE CORRECTLY FORMATTED JSON WITHOUT ANY ESCAPE CHARACTERS 
    JsonObject obj = JsonObject.Parse(feed_data); // <-- THROWS AN "INVALID JSON ERROR HERE" AND VALUE OF VARIABLE IN AUTOS SHOWS JSON DATA WITH ESCAPE CHARACTERS AND ADDITIONAL QUOTATION MARKS BEFORE AND AFTER THE STRING 
} 

private string getFeed() 
{ 
    HttpClient client = new HttpClient(); 
    string url = "URL HERE"; 
    HttpResponseMessage response = client.GetAsync(url).Result; 
    return response.Content.ReadAsStringAsync().Result; 
} 

那么这里发生了什么问题?执行Debug.WriteLine(feed_data);行时,我在输出控制台中看到有效的JSON,但仍然出现分析错误。


编辑:样品JSON(预期并显示在控制台中的一个):

[{"id":"884","author":"795","title":"The sum of ages of 5 children born at the intervals of 3 years each is 50 years. What is the age of the youngest child?","details":" ","datetime":"1439099443","answered":"1","vote":"0","answers":[{"id":"884","author":"788","answer":"4 years","datetime":"1439165670","votes":"0"}]}]

VS的JSON在汽车窗,什么解析失败的:

"[{\"id\":\"884\",\"author\":\"795\",\"title\":\"The sum of ages of 5 children born at the intervals of 3 years each is 50 years. What is the age of the youngest child?\",\"details\":\" \",\"datetime\":\"1439099443\",\"answered\":\"1\",\"vote\":\"0\",\"answers\":[{\"id\":\"884\",\"author\":\"788\",\"answer\":\"4 years\",\"datetime\":\"1439165670\",\"votes\":\"0\"}]}]"

+0

显示JSON数据发现错误 – Backs

您的JSON字符串表示JSON数组而不是JSON对象。使用JSON.NET(我没有开发环境在UWP中测试)我通过做JObject.Parse(feed_data)得到了相同的错误,并且可以通过使用JArray.Parse(feed_data)来修复它。所以,我强烈怀疑,在UWP,等效解决方案将使用JsonArray.Parse()

JsonArray arr = JsonArray.Parse(feed_data); 
+0

应标记为回答! –