本文介绍了从调用asp.net C#外部JSON web服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从C#Asp.net一个JSON web服务的调用。该服务将返回一个JSON对象和web服务要像这样JSON数据:

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:

"data" : "my data"

这是什么我已经出来了,但我不明白我是如何将数据添加到我的请求,并将其发送,然后分析我找回了JSON数据。

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.

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数据添加到我的请求,然后解析响应?

How can I add my json data to my request and then parse the response?

推荐答案

使用的JavaScriptSerializer,反序列化/分析数据。您可以通过获取数据:

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
    }
}

这篇关于从调用asp.net C#外部JSON web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 07:28