Get JSON response using RestSharp

梦想与她 提交于 2020-01-02 00:51:16

问题


I'm new to C# and I'm trying to get the JSON response from a REST request using RestSharp; The request I want to execute is the following one : "http://myurl.com/api/getCatalog?token=saga001". It works great if I'm executing it in a browser.

I've tried this :

var client = new RestClient("http://myurl.com/api/");

var request = new RestRequest("getCatalog?token=saga001"); 

var queryResult = client.Execute(request);

Console.WriteLine(queryResult);

And I get "RestSharp.RestReponse" instead of the JSON result I'm hopping for.

Thanks for your help !


回答1:


Try:

var client = new RestClient("http://myurl.com/api/");

var request = new RestRequest("getCatalog?token={token}", Method.GET); 

request.AddParameter("token", "saga001", ParameterType.UrlSegment);   

// request.AddUrlSegment("token", "saga001"); 

request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

var queryResult = client.Execute(request);

Console.WriteLine(queryResult.Content);



回答2:


Try as below:

var client = new RestClient("http://myurl.com/api/");

client.ClearHandlers();
var jsonDeserializer = new JsonDeserializer();
client.AddHandler("application/json", jsonDeserializer);

var request = new RestRequest("getCatalog?token=saga001"); 

var queryResult = client.Execute(request);

Console.WriteLine(queryResult);



回答3:


This is old but I was just struggling with this too. This is the easiest way I found.

var client = new RestClient("http://myurl.com/api/");
var request = new RestRequest("getCatalog?token=saga001"); 
var response = client.Execute(request);

if (response.StatusCode == HttpStatusCode.OK)
{
    // Two ways to get the result:
    string rawResponse = response.Content;
    MyClass myClass = new JsonDeserializer().Deserialize<MyClass>(response);
}



回答4:


If you want to save the result into JSON file: You should use these namespaces:

using RestSharp;

using Newtonsoft.Json;

using Newtonsoft.Json.Linq;

var client = new RestClient("http://myurl.com/api/");
var request = new RestRequest(Method.GET);
request.AddHeader("content-type", "application/json");
var queryResult = client.Execute<Object>(request).Data;
string json = JsonConvert.SerializeObject(queryResult);
System.IO.File.WriteAllText(@"C:\...\path.json", json);


来源:https://stackoverflow.com/questions/23086825/get-json-response-using-restsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!