开发者

Deserialize Json to class object using restsharp

I have checked out the documentation for restsharp and also googled for a solution, but unable to find a solution for this problem:

I have an asp.net mvc3 app and need to connect to quizlet.com to access public flashcards. I have added a reference to restsharp and created the following classes:

public class QuizletObject
{
    public string response_type { get; set; }
    public int total_results { get; set; }
    public int page { get; set; }
    public int total_pages { get; set; }
    public int sets_with_images { get; set; }
    public Set[] sets { get; set; }
}

public class Set
{
    public int id { get; set; }
    public string title { get; set; }
    public string url { get; set; }
    public string creator { get; set; }
    public int created { get; set; }
    public int term_count { get; set; }
    public bool has_images { get; set; }
    public int last_modified { get; set; }
}

I have a class and method that calls the web service like this:

public class Quizlet
{
    private string _baseUrl = "http://api.quizlet.com/1.0/sets";
    private const string DevKey = "my dev key";               

    public QuizletObject GetQuizletSets()
    {
        _baseUrl = _baseUrl + "?dev_key=" + DevKey + "&q=" + "geography";

        RestClient client = new RestClient();
        client.BaseUrl = _baseUrl;

        RestRequest request = new RestRequest(Method.GET);
        r开发者_如何学运维equest.RequestFormat = DataFormat.Json;

        RestResponse<QuizletObject> response = client.Execute<QuizletObject>(request);

        return response.Data;
    }
}

When I try to access the method using the below code in the view, I get a NullReference exception (Object reference not set to an instance of an object).

@{
QuizletObject quizletObject = quizlet.GetQuizletSets();
}

@foreach (Set quizletSet in quizletObject.sets)
{
    @quizletSet.id.ToString()
    <br />
    @quizletSet.title
    <br />
    @quizletSet.creator
    <br />
    @quizletSet.created
    <br />
    @Html.Encode(quizletSet.url)    
    <br />
    <br />
}    

If the same method is executed as below, it returns the complete json object without any problem

RestResponse response = client.Execute(request);

Stack trace:

[NullReferenceException: Object reference not set to an instance of an object.]
ASP._Page_Views_Home_Index_cshtml.Execute() in c:\Users\Girish\Documents\Visual Studio 2010\Projects\RestSharpPoC\RestSharpPoC\Views\Home\Index.cshtml:18
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +207
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +81
System.Web.WebPages.StartPage.RunPage() +19
System.Web.WebPages.StartPage.ExecutePageHierarchy() +65
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +220
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +303
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +260
System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8963149
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184


I have seen the same issue. I haven't figured it out in RestSharp, but what I do to work around it is get the json text back then deserialize it myself.

For your code maybe something like this would work:

response = client.Execute(request);
var quizletObject = Newtonsoft.Json.JsonConvert.DeserializeObject<QuizletObject>(response.Content);

As an aside, it looks like you have a problem in your GetQuizletSets() call - each time you call it, it appends _baseUrl to itself so it will continually get longer and longer.

You should keep the base url the same and use request.Resource to specify the parameters, this case it would be:

request.Resource = "?dev_key=" + DevKey + "&q=" + "geography" 

If there are multiple available calls you want to make besides "sets" I might set it up like this:

private string _baseUrl = "http://api.quizlet.com/1.0";
...
request.Resource = "sets?dev_key=" + DevKey + "&q=" + "geography";

Edit: Just thought of something else - try using List instead of Set[], maybe RestSharp will have an easier time with that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜