[英]RestSharp fails on saving results
Response is successful, i can view it in Visual Studio, but when i try to get returned data, its null.响应成功,我可以在 Visual Studio 中查看它,但是当我尝试获取返回的数据时,它的 null。
This is API https://yoda-api.appspot.com/api/v1/yodish?text=I%20am%20yoda这是 API https://yoda-api.appspot.com/api/v1/yodish?text=I%20am%20yoda
And this is my code:这是我的代码:
public class YodishModel { public string yodish { get; set; } } public class YodishResult { public YodishModel Result { get; set; } } public class YodishService : iService { public string GetText(string text) { Lazy<RestClient> client = new Lazy<RestClient>(() => new RestClient($"http://yoda-api.appspot.com/api/v1/yodish?text={text}")); var request = new RestRequest(); var response = client.Value.Execute<YodishResult>(request); if (response.IsSuccessful) { return response.Data.Result.yodish; } return null; } public string ToUrl(string text) { return HttpUtility.UrlEncode(text); } }
Response is successful, i can view the result, but Result
is null ( NullPointerException
).响应成功,我可以查看结果,但
Result
是 null ( NullPointerException
)。
Also, is there a way to use parameters here instead of using string interpolation?另外,有没有办法在这里使用参数而不是使用字符串插值? 'text' is part of the URL which is officially not a paremeter.
'text' 是 URL 的一部分,官方不是参数。
In your case, you were deserializing using a mismatched object.在您的情况下,您使用不匹配的 object 进行反序列化。 This is what I did to fix it:
这是我为解决它所做的:
public class YodishModel
{
public string yodish { get; set; }
}
public class YodishService
{
public string GetText(string text)
{
Lazy<RestClient> client = new Lazy<RestClient>(() => new RestClient($"https://yoda-api.appspot.com/api/v1/"));
var request = new RestRequest($"yodish").AddQueryParameter("text", Uri.EscapeDataString(text), true);
var response = client.Value.Execute<YodishModel>(request);
if (response.IsSuccessful)
{
return Uri.UnescapeDataString(response.Data.yodish);
}
return null;
}
}
I also added the AddQueryParameter, as you mentioned.正如您提到的,我还添加了 AddQueryParameter。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.