gpt4 book ai didi

c# - 如何从 REST Web 服务返回自定义值

转载 作者:太空宇宙 更新时间:2023-11-03 15:54:32 25 4
gpt4 key购买 nike

我在我的项目中使用 REST Web 服务,它的返回值在 json 中,如下所示:

[{"MsgID":"92817137","Status":"0","SendTime":"2014-06-11 14:17:40","DeliverTime":"0000-00- 00 00:00:00"}]

但我不需要所有这些,我只需要“Statues”标签。我该怎么做?

我的代码是这样的:

    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"

谢谢

最佳答案

如果您无法更改网络服务的方法以使其仅返回您需要的值,唯一的方法是在您的代码中自定义响应。

// 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();

}

关于c# - 如何从 REST Web 服务返回自定义值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24159878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com