在C#中下载JSON字符串

Aim*_*nes 9 .net c# string json

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

{
 "status": "okay",
 "result": {"id":"1",
            "type":"monument",
            "description":"The Spire",
            "latitude":"53.34978",
            "longitude":"-6.260316",
            "private": "{\"tag\":\"david\"}"}
}
Run Code Online (Sandbox Code Playgroud)

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

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
}
Run Code Online (Sandbox Code Playgroud)

我一直在环顾四周,看到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();
}
Run Code Online (Sandbox Code Playgroud)

谁知道我哪里出错了?提前致谢!

ema*_*tel 17

您正在输出服务器响应.服务器响应包含a StreamContent(请参阅此处的文档),但这StreamContent没有定义a ToString,因此输出类名而不是内容.

ReadAsStringAsync(此处的文档)是获取服务器发回的内容的正确方法.您应该打印出此调用的返回值:

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;
}
Run Code Online (Sandbox Code Playgroud)