【问题标题】:Console shows correctly-formatted JSON, but JsonObject is unable to parse it控制台显示格式正确的 JSON,但 JsonObject 无法解析它
【发布时间】:2015-11-01 06:25:25
【问题描述】:

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

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"}]}]

对比自动窗口中的 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\"}]}]"

【问题讨论】:

  • 显示json数据查找错误

标签: c# .net json uwp


【解决方案1】:

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

JsonArray arr = JsonArray.Parse(feed_data); 

【讨论】:

    猜你喜欢
    • 2013-04-10
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    相关资源
    最近更新 更多