【问题标题】:Download a JSON String in C#在 C# 中下载 JSON 字符串
【发布时间】:2012-11-22 15:29:36
【问题描述】:

我正在尝试在我的 Windows 应用商店应用程序中下载一个 JSON 字符串,它应该如下所示:

{
 "status": "okay",
 "result": {"id":"1",
            "type":"monument",
            "description":"The Spire",
            "latitude":"53.34978",
            "longitude":"-6.260316",
            "private": "{\"tag\":\"david\"}"}
}

但我得到了关于服务器的信息。我得到的输出如下:

Response: StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  MS-Author-Via: DAV
  Keep-Alive: timeout=15, max=100
  Connection: Keep-Alive
  Date: Thu, 22 Nov 2012 15:13:53 GMT
  Server: Apache/2.2.22
  Server: (Unix)
  Server: DAV/2
  Server: PHP/5.3.15
  Server: with
  Server: Suhosin-Patch
  Server: mod_ssl/2.2.22
  Server: OpenSSL/0.9.8r
  X-Powered-By: PHP/5.3.15
  Content-Length: 159
  Content-Type: text/json
}

我环顾四周,发现 WebClient 在 Windows 8 之前使用,现在被 HttpClient 取代。因此,我一直在使用 Content.ReadAsString(),而不是使用 DownloadString()。这是我到目前为止的一些代码:

public async Task<string> GetjsonStream()
{
    HttpClient client = new HttpClient();
    string url = "http://(urlHere)";
    HttpResponseMessage response = await client.GetAsync(url);
    Debug.WriteLine("Response: " + response);
    return await response.Content.ReadAsStringAsync();
}

有人知道我哪里出错了吗? 提前致谢!

【问题讨论】:

标签: c# .net json string


【解决方案1】:

您正在输出服务器响应。服务器响应包含一个StreamContent(参见文档here),但这个StreamContent 没有定义ToString,所以输出的是类名而不是内容。

ReadAsStringAsync(文档here)是获取服务器发回内容的正确方法。你应该打印出这个调用的返回值:

public async Task<string> GetjsonStream()
{
    HttpClient client = new HttpClient();
    string url = "http://(urlHere)";
    HttpResponseMessage response = await client.GetAsync(url);
    string content = await response.Content.ReadAsStringAsync();
    Debug.WriteLine("Content: " + content);
    return content;
}

【讨论】:

  • 感谢 emartel。我现在知道了。我没有字符串中的实际内容,而您添加的行提供了一种正确输出字符串的方法。我认为这就是您的意思。 :) 救了我很多痛苦和头痛!再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-18
  • 1970-01-01
相关资源
最近更新 更多