Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从asp.net C调用外部json Web服务#_Asp.net_Web Services_Json - Fatal编程技术网

从asp.net C调用外部json Web服务#

从asp.net C调用外部json Web服务#,asp.net,web-services,json,Asp.net,Web Services,Json,我需要从C#Asp.net调用json Web服务。服务返回一个json对象,Web服务想要的json数据如下所示: "data" : "my data" 这就是我想到的,但我不明白如何将数据添加到请求并发送,然后解析返回的json数据 string data = "test"; Uri address = new Uri("http://localhost/Service.svc/json"); HttpWebRequest request = (HttpWebRequest)WebRequ

我需要从C#Asp.net调用json Web服务。服务返回一个json对象,Web服务想要的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数据添加到请求中,然后解析响应?

使用,来反序列化/解析数据。您可以使用以下方式获取数据:

// 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
    }
}
可能重复: