C# 如何使用web客户端解析json并在控制台中显示它?
错误消息显示:C# 如何使用web客户端解析json并在控制台中显示它?,c#,windows-phone-8,C#,Windows Phone 8,错误消息显示: “System.Net.WebClient”不包含“DownloadString”的定义,并且找不到接受“System.Net.WebClient”类型的第一个参数的扩展方法“DownloadString”(您是否缺少using指令或程序集引用?在windows phone中,在大多数情况下,您被迫以异步方式编程。 因此,您必须使用DownloadStringAsync,而不是DownloadString,如本示例所示: WebClient client = new WebCli
“System.Net.WebClient”不包含“DownloadString”的定义,并且找不到接受“System.Net.WebClient”类型的第一个参数的扩展方法“DownloadString”(您是否缺少using指令或程序集引用?在windows phone中,在大多数情况下,您被迫以异步方式编程。 因此,您必须使用DownloadStringAsync,而不是DownloadString,如本示例所示:
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.Http添加,并使用System.Net.Http.Header添加
我没有在您的特定场景或服务中测试过这一点,但我不明白为什么它不适用于您,因为它是异步获取JSON的
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);
}
//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;