如何使用Web客户端解析json并将其显​​示在控制台中?

时间:2014-03-14 01:32:29

标签: c# windows-phone-8

WebClient client = new WebClient();

string value = client.DownloadString("http://www.onemap.sg/publictransportation/service1.svc/routesolns?token=qo/s2TnSUmfLz+32CvLC4RMVkzEFYjxqyti1KhByvEacEdMWBpCuSSQ+IFRT84QjGPBCuz/cBom8PfSm3GjEsGc8PkdEEOEr&sl=39167.4524,35518.8625&el=28987.5163,33530.5653&startstop=&endstop=&walkdist=300&mode=bus&routeopt=cheapest&retgeo=true&maxsolns=1&callback=");

 // Write values.
 Console.WriteLine("Results:");
 Console.WriteLine(value.Length);
 Console.WriteLine(value);

错误消息显示: 'System.Net.WebClient'不包含'DownloadString'的定义,也没有可以找到接受类型'System.Net.WebClient'的第一个参数的扩展方法'DownloadString'(你是否缺少using指令或程序集引用?)

2 个答案:

答案 0 :(得分:1)

在Windows手机中,您在大多数情况下都被迫以异步方式进行编程。 因此,不必使用DownloadString,而是必须使用DownloadStringAsync,如下例所示:

  var client = new WebClient();

  client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(loadHTMLCallback);
  client.DownloadStringAsync(new Uri("http://www.myurl.com/myFile.txt"));
//...

public void loadHTMLCallback(Object sender, DownloadStringCompletedEventArgs e)
{
  var textData = (string)e.Result;
  // Do cool stuff with result
  Debug.WriteLine(textData);
}

来源: http://developer.nokia.com/community/wiki/Asynchronous_Programming_For_Windows_Phone_8

答案 1 :(得分:0)

//Initialize new Client
HttpClient client = new HttpClient();
//Response will handle the returned JSON
HttpResponseMessage response;

//URI of the service
string strURI = "http://www.onemap.sg/publictransportation/service1.svc/routesolns?token=qo/s2TnSUmfLz+32CvLC4RMVkzEFYjxqyti1KhByvEacEdMWBpCuSSQ+IFRT84QjGPBCuz/cBom8PfSm3GjEsGc8PkdEEOEr&sl=39167.4524,35518.8625&el=28987.5163,33530.5653&startstop=&endstop=&walkdist=300&mode=bus&routeopt=cheapest&retgeo=true&maxsolns=1&callback=";

//String that the response will be converted to.
string strResponseJSONContent = "";

//Lets the client know to expect JSON
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

//Getting the JSON and saving it to response
response = client.GetAsync(strURI).Result;

//Setting response to a string
strResponseJSONContent = response.Content.ReadAsStringAsync().Result;

您需要添加using System.Net.Httpusing System.Net.Http.Headers

我还没有在您的特定场景或您的服务中对此进行测试,但我无法理解为什么它不能为您工作,因为它会异步获取JSON。