在C#中下载一个JSON字符串

12

我正在尝试在我的Windows Store应用程序中下载一个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所取代。因此,我不再使用DownloadString(),而是使用Content.ReadAsString()。以下是我目前的代码片段:

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

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


既然您没有在其他地方使用响应,为什么不直接使用HttpClient.GetStringAsync呢? - khellang
2个回答

23
您正在输出服务器响应。服务器响应包含一个StreamContent(请参见此处的文档),但是这个StreamContent没有定义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;
}

谢谢 emartel。我现在明白了。我没有将实际内容放在字符串中,你添加的那行提供了一个正确输出字符串的方法..好吧,我想这就是你的意思。:)虽然如此,但你救了我很多麻烦和头痛!再次感谢! - Aimee Jones

0

如果您在await块内部,可能需要获取Result ReadAsStringAsync().Result。

例如:

public async Task<HttpResponseMessage> Listen()
{
   await Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(
      new MultipartMemoryStreamProvider()).ContinueWith(task =>
      {
         MultipartMemoryStreamProvider multipartMemoryStreamProvider = task.Result;

         var imageContent = multipartMemoryStreamProvider.Contents.First();
         string name = imageContent.Headers.ContentDisposition.Name;
         string fileName = imageContent.Headers.ContentDisposition.FileName;
         data = imageContent.ReadAsByteArrayAsync().Result;

         string content = multipartMemoryStreamProvider.Contents.Last().ReadAsStringAsync().Result;

         model = multipartMemoryStreamProvider.Contents.Last().ReadAsAsync<RecordingModel>().Result;
      }
   );
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接