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

时间:2011-09-29 11:16:40

标签: asp.net-mvc-3 restsharp

我已经检查了restsharp的文档,并且还搜索了一个解决方案,但无法找到解决此问题的方法:

我有一个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

1 个答案:

答案 0 :(得分:3)

我见过同样的问题。我还没有在RestSharp中找到它,但是我要解决的问题是将json文本取回然后自行反序列化。

对于你的代码,这样的东西可能会起作用:

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

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

你应该保持基本URL相同并使用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会有更轻松的时间。