Я должен позвонить json веб-сервису с Asp.net C#. Сервис возвращает объект json и 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 данные к моему запросу и затем проанализировать ответ?
Использование JavaScripterializer , для десериализации / анализа данных. Вы можете получить данные, используя:
// 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
}
}