使用 RestSharp 反序列化列表时获取空值 [英] Getting null values when deserializing a list using RestSharp

查看:97
本文介绍了使用 RestSharp 反序列化列表时获取空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C# 和 RestSharp 的新手.

I am new to C# and to RestSharp.

我正在编写一个小程序来通过 REST 检索记录列表.我已经能够检索到一项记录.现在我需要得到一个记录列表,这里我有一个问题.

I am writing a small program to retrieve a list of records via REST. I have been able to retrieve one record. Now I need to get a list of records, and here I have a problem.

我使用 SoapUI 得到的响应如下所示:

The response I get using SoapUI looks like this:

{
   "@count": 2,
   "@start": 1,
   "@totalcount": 2,
   "Messages": [],
   "ResourceName": "email",
   "ReturnCode": 0,
   "content":    [
      {"email": {"evsysseq": "0000000000000262"}},
      {"email": {"evsysseq": "0000000000000263"}}
   ]
}

我的代码如下所示:

class EmailID
{
    public string Evsysseq { get; set; }
}

var client = new RestClient("xxxxx");
client.Authenticator = new HttpBasicAuthenticator("xxx", "xxx");
string queryParm = HttpUtility.UrlEncode("evsysseq>\"0000000000000261\"");

var request = new RestRequest("xxxx?query="+ queryParm, Method.GET);
request.RootElement = "content";
var queryResult = client.Execute<List<EmailID>>(request).Data;

运行它不会导致错误,而且我可以在 queryResult 对象上看到它确实包含两条记录.但是,Evsysseq 在两者上都是空的,这就是我的问题.我不知道要调整什么才能使它正确.

Running it does not result in errors, and I can see on the queryResult object that it does contain two records. But, Evsysseq is null on both, and that is my problem. I am not sure what to tweak to get it right.

推荐答案

您得到空值,因为您反序列化的 JSON 与您反序列化成的类结构不匹配.您告诉 RestSharp 将 content 数组反序列化为 List,但 JSON 确实表示 包含 EmailID 对象.所以你需要另一个类:

You are getting null values because the JSON you are deserializing does not match the class structure you are deserializing into. You are telling RestSharp to deserialize the content array into a List<EmailID>, but the JSON really represents a list of objects that contain EmailID objects. And so you need another class:

class EmailObj
{
    public EmailID Email { get; set; }
}

然后像这样反序列化,你应该得到数据:

Then deserialize like this and you should get the data:

var queryResult = client.Execute<List<EmailObj>>(request).Data;

如果您愿意,您可以使用 LINQ 来获取您最初想要的 List,如下所示:

If you want to, you can then use LINQ to get the List<EmailID> that you originally wanted like this:

var emailIds = queryResult.Select(eo => eo.Email).ToList();

HTH

这篇关于使用 RestSharp 反序列化列表时获取空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆