2012-11-22 13 views
8

Sto cercando di scaricare una stringa JSON in mio Windows App Store, che dovrebbe assomigliare a questo:scaricare una stringa JSON in C#

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

ma sto ottenendo quello che sembra informazioni relative al server. L'uscita sto ottenendo è il seguente:

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 
} 

Ho cercato in giro e vedo che WebClient è stato utilizzato prima di Windows 8, ed è ora sostituito con HttpClient. Quindi, invece di usare DownloadString(), sto usando Content.ReadAsString(). Ecco il bit di codice che ho finora:

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

Qualcuno sa dove sto andando male? Grazie in anticipo!

+0

Poiché non stai utilizzando la risposta per nient'altro. Perché non usi semplicemente ['HttpClient.GetStringAsync'] (http://msdn.microsoft.com/en-us/library/hh551746.aspx)? – khellang

risposta

14

Si sta emettendo la risposta del server. La risposta del server contiene StreamContent (vedere la documentazione here) ma questo StreamContent non definisce un ToString, quindi il nome della classe viene emesso al posto del contenuto.

ReadAsStringAsync (documentazione here) è il metodo giusto per ottenere il contenuto inviato dal server. Dovresti invece stampare il valore di ritorno di questa chiamata:

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; 
} 
+0

Grazie emartel. Ora capisco. Non avevo il contenuto reale in una stringa e la linea che hai aggiunto fornisce un modo per produrre correttamente la stringa .. beh, penso che sia quello che intendi. :) Mi ha risparmiato un sacco di dolore e mal di testa! Grazie ancora! –