I need to make a call to a json webservice from C# Asp.net. The service returns a json object and the json data that the webservice wants look like this:
我需要从c# Asp.net调用一个json webservice。该服务返回一个json对象,webservice想要的json数据如下所示:
"data" : "my data"
This is what I've come up with but I can't understand how I add the data to my request and send it and then parse the json data that I get back.
这是我想到的,但是我不明白如何将数据添加到请求中,然后发送它,然后解析返回的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 + "\"}";
How can I add my json data to my request and then parse the response?
如何将json数据添加到请求中,然后解析响应?
1 个解决方案
#1
16
Use the JavaScriptSerializer, to deserialize/parse the data. You can get the data using:
使用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
}
}
#1
16
Use the JavaScriptSerializer, to deserialize/parse the data. You can get the data using:
使用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
}
}