简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM