2010-01-15 12 views
9

से बाहरी जेसन webservice पर कॉल करें मुझे सी # Asp.net से एक जेसन webservice पर कॉल करने की आवश्यकता है। सेवा एक json वस्तु और json डेटा वेब सेवा इस तरह दिखना चाहता है कि रिटर्न:एएसपीनेट सी #

"data" : "my data" 

यह है कि मैं क्या लेकर आए हैं, लेकिन मैं नहीं समझ सकता कैसे मैं अपने अनुरोध करने के लिए डेटा जोड़ने और भेज है यह और फिर जेसन डेटा को पार्स करें जो मैं वापस आऊंगा।

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 + "\"}"; 

मैं अपने अनुरोध में अपना जेसन डेटा कैसे जोड़ सकता हूं और फिर प्रतिक्रिया को पार्स कर सकता हूं?

+0

संभावित डुप्लिकेट: http://stackoverflow.com/questions/8270464/best-way-to-call-a-json-webservice-from-a-net-console/ 8270482 # 8270482 –

उत्तर

16

डेटा को deserialize/पार्स करने के लिए 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 
    } 
}