如何解析System.Net.Webrequest响应中的JSON数据
本文关键字:JSON 数据 响应 Webrequest 何解析 System Net | 更新日期: 2023-09-27 18:06:20
我试图调用一个API,它返回JSON格式的数据,我需要解析。如何在System.Net.Webrequest中做到这一点…下面是我的代码
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
request = WebRequest.Create("https://IPAaddress/api/admin/configuration/v1/conference/1/");
request.Credentials = new NetworkCredential("username", "password");
// Create POST data and convert it to a byte array.
request.Method = "GET";
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json; charset=utf-8";
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
Webrequest只是返回一个来自远程资源的响应。您需要自己解析JSON,比如使用DataContractJsonSerializer或JSON。网(http://www.newtonsoft.com/json)
谢谢大家我的问题得到了解决,下面是代码…
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
request = WebRequest.Create("https://ipaddress/api/admin/configuration/v1/conference/1/");
request.Credentials = new NetworkCredential("admin", "admin123");
// Create POST data and convert it to a byte array.
request.Method = "GET";
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json; charset=utf-8";
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
JavaScriptSerializer js = new JavaScriptSerializer();
var obj = js.Deserialize<dynamic>(responseFromServer);
Label1.Text = obj["name"];
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();