我有一个Web服务,它接收一个json字符串并返回json字符串。但是在收到httpwebresponse形式的响应时,我得到了 { “年龄”: “29”, “姓名”: “亚历克斯”}。
我怎样才能得到{“age”:“29”,“name”:“Alex”}因为上面的回复没有被反序列化。
详细信息类:
public class Details
{
public String name { get; set; }
public String age { get; set; }
}
网络服务代码:
[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"}
答案 0 :(得分:0)
当您在JSON格式化的响应中发送数据并期望数据时,请尝试将内容标题更改为application / json:
httpWebRequest.ContentType = "application/json; charset=utf-8";
您也可以设置接受标头:
httpWebRequest.Accept = "application/json;";