Reputation: 99
Response is successful, i can view it in Visual Studio, but when i try to get returned data, its null.
This is 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
).
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.
Upvotes: 1
Views: 421
Reputation: 377
In your case, you were deserializing using a mismatched 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.
Upvotes: 1