正在从web服务的httpresponse中检索json响应
本文关键字:检索 json 响应 httpresponse web 服务 | 更新日期: 2023-09-27 18:29:19
我有一个web服务,它接收json字符串并返回json字符串。但在收到httpwebresponse形式的响应后,我得到{"年龄":"29","姓名":"亚历克斯"}。
我怎么能只得到{"age":"29","name":"Alex"},因为上面的响应没有被反序列化。
详细信息类别:
public class Details
{
public String name { get; set; }
public String age { get; set; }
}
Web服务代码:
[WebMethod]
[ScriptMethod(UseHttpGet=true, ResponseFormat = ResponseFormat.Json)]
public String getDetails(String details)
{
Details d;
Details retval=(Details)new JavaScriptSerializer().Deserialize(details, typeof(Details));
retval.age = 29.ToString();
String result = new JavaScriptSerializer().Serialize(retval);
return result;
}
客户端代码:
class Program
{
static void Main(string[] args)
{
Details details = new Details();
details.name = "John";
details.age = "24";
String jsonString = new JavaScriptSerializer().Serialize(details);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost/JsonService/service1.asmx/getDetails");
httpWebRequest.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
jsonString="details="+jsonString;
streamWriter.Write(jsonString);
}
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
}
The value of **result** comes as <?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">{"age":"29","name":"Alex"}</string>
but I need only {"age":"29","name":"Alex"}
当您发送数据并期望在JSON格式的响应中返回数据时,请尝试将内容标头更改为application/JSON:
httpWebRequest.ContentType = "application/json; charset=utf-8";
您也可以设置接受标头:
httpWebRequest.Accept = "application/json;";