我需要调用来自C#Asp.net的json webservice。该服务返回一个json对象,webservice想要的json数据如下所示:
"data" : "my data"
这是我想出来的,但我无法理解如何将数据添加到我的请求并发送它然后解析我得到的json数据。
string data = "test";
Uri address = new Uri("http://localhost/Service.svc/json");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
string postData = "{\"data\":\"" + data + "\"}";
如何将我的json数据添加到我的请求中,然后解析响应?
答案 0 :(得分:16)
使用JavaScriptSerializer来反序列化/解析数据。您可以使用以下方式获取数据:
// corrected to WebRequest from HttpWebRequest
WebRequest request = WebRequest.Create("http://localhost/service.svc/json");
request.Method="POST";
request.ContentType = "application/json; charset=utf-8";
string postData = "{\"data\":\"" + data + "\"}"; //encode your data
//using the javascript serializer
//get a reference to the request-stream, and write the postData to it
using(Stream s = request.GetRequestStream())
{
using(StreamWriter sw = new StreamWriter(s))
sw.Write(postData);
}
//get response-stream, and use a streamReader to read the content
using(Stream s = request.GetResponse().GetResponseStream())
{
using(StreamReader sr = new StreamReader(s))
{
var jsonData = sr.ReadToEnd();
//decode jsonData with javascript serializer
}
}