如何从REST Web服务返回自定义值
本文关键字:返回 自定义 服务 Web REST | 更新日期: 2023-09-27 18:08:11
我在我的项目中使用REST web服务,它的返回值是json格式,如下所示:
[{"MsgID":"92817137","Status":"0","SendTime":"2014-06-11 14:17:40","DeliverTime":"0000-00-00 00:00:00"}]
但是我不需要所有这些,我只需要"雕像"标签。我怎么能做到呢?
我的代码是这样的: private void btnCheckStatus_Click(object sender, EventArgs e)
{
Uri address = new Uri("http://www.asanak.ir/webservice/v1rest/msgstatus");
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Create the data we want to send
StringBuilder data = new StringBuilder();
data.Append("username=" + textUserName.Text.Trim());
data.Append("&password=" + textPassword.Text.Trim());
data.Append("&msgid=" + textMsgId.Text.Trim());
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
textResult.Text = reader.ReadToEnd();
}
}
我希望我的返回值是这样的:"Status":"0"
谢谢
如果您不能更改webservice的方法使其只返回您需要的值,那么唯一的方法是在代码中自定义响应。
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
//add your code here to customize the return value
var array = Newtonsoft.Json.Linq.JArray.Parse(reader.ReadToEnd());
var jObject = new Newtonsoft.Json.Linq.JObject();
jObject.Add("Status", array[0].Value<string>("Status"));
textResult.Text = jObject.ToString();
}