使用restsharp将Json反序列化为类对象

发布于 2024-12-07 08:09:05 字数 4771 浏览 0 评论 0原文

我已经检查了 Restsharp 的文档,并在 google 上搜索了解决方案,但无法找到此问题的解决方案:

我有一个 asp.net mvc3 应用程序,需要连接到 quizlet.com 才能访问公共抽认卡。我添加了对 Restsharp 的引用并创建了以下类:

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; }
}

我有一个类和方法调用 Web 服务,如下所示:

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);
        request.RequestFormat = DataFormat.Json;

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

        return response.Data;
    }
}

当我尝试在视图中使用以下代码访问该方法时,我收到 NullReference 异常(对象引用未设置为对象的实例)。

@{
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 />
}    

如果执行如下相同的方法,它将返回完整的 json 对象,没有任何问题

RestResponse response = client.Execute(request);

堆栈跟踪:

[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 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);
        request.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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你曾走过我的故事 2024-12-14 08:09:05

我也看到过同样的问题。我还没有在 RestSharp 中弄清楚它,但我所做的解决方法是获取 json 文本,然后自己反序列化它。

对于您的代码,也许这样的事情会起作用:

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

顺便说一句,您的 GetQuizletSets() 调用似乎有问题 - 每次调用它时,它都会将 _baseUrl 附加到自身,因此它会不断变得越来越长。

您应该保持基本网址相同并使用 request.Resource 来指定参数,这种情况是:

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

如果除了“集”之外您还想进行多个可用调用,我可能会这样设置:

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

编辑:只是想其他的东西 - 尝试使用 List 而不是 Set[],也许 RestSharp 会更轻松。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文