我如何用web客户端解析json并在控制台中显示它
本文关键字:控制台 显示 json 何用 web 客户端 | 更新日期: 2023-09-27 17:50:22
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'的定义,也没有扩展方法'DownloadString'接受第一个参数类型为'System.Net '。
在windows phone中,大多数情况下你都被迫以异步方式编程。因此,你必须使用DownloadStringAsync而不是DownloadString,如下面的示例所示:
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
//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.Http
和using System.Net.Http.Headers
我还没有在你的特定场景或服务中测试过这个,但我不明白为什么它不能为你工作,因为它异步获取JSON