Call external json webservice from asp.net C#

后端 未结 1 1958
攒了一身酷
攒了一身酷 2020-12-25 08:29

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:

\"d         


        
相关标签:
1条回答
  • 2020-12-25 09:06

    Use the JavaScriptSerializer, to deserialize/parse the data. You can get the data using:

    // 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
        }
    }
    
    0 讨论(0)
提交回复
热议问题