从.NET 控制台调用 JSON WebService 的最佳方式

我在 ASP.Net MVC3中托管了一个 Web 服务,它返回一个 Json 字符串。从 c # 控制台应用调用 webservice 并将返回值解析为。NET 对象?

我应该在控制台应用程序中引用 MVC3吗?

杰森。Net 有一些很好的序列化和反序列化方法。NET 对象,但是我没有看到它有从一个 webservice 发布和获取值的方法。

或者我应该创建自己的 helper 方法来 POSTing 和 GEting 到 Web 服务?我该如何连载我的。从 net 对象到键值对?

212415 次浏览

WebClient to fetch the contents from the remote url and JavaScriptSerializer or Json.NET to deserialize the JSON into a .NET object. For example you define a model class which will reflect the JSON structure and then:

using (var client = new WebClient())
{
var json = client.DownloadString("http://example.com/json");
var serializer = new JavaScriptSerializer();
SomeModel model = serializer.Deserialize<SomeModel>(json);
// TODO: do something with the model
}

There are also some REST client frameworks you may checkout such as RestSharp.

I use HttpWebRequest to GET from the web service, which returns me a JSON string. It looks something like this for a GET:

// Returns JSON string
string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try {
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex) {
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}

I then use JSON.Net to dynamically parse the string. Alternatively, you can generate the C# class statically from sample JSON output using this codeplex tool: http://jsonclassgenerator.codeplex.com/

POST looks like this:

// POST a JSON string
void POST(string url, string jsonContent)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";


System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);


request.ContentLength = byteArray.Length;
request.ContentType = @"application/json";


using (Stream dataStream = request.GetRequestStream()) {
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try {
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
length = response.ContentLength;
}
}
catch (WebException ex) {
// Log exception and throw as for GET example above
}
}

I use code like this in automated tests of our web service.

Although the existing answers are valid approaches , they are antiquated . HttpClient is a modern interface for working with RESTful web services . Check the examples section of the page in the link , it has a very straightforward use case for an asynchronous HTTP GET .

using (var client = new System.Net.Http.HttpClient())
{
return await client.GetStringAsync("https://reqres.in/api/users/3"); //uri
}