问题
I am new to C# and to RestSharp.
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.
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"}}
]
}
My code looks like this:
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;
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.
回答1:
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;
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
来源:https://stackoverflow.com/questions/41384385/getting-null-values-when-deserializing-a-list-using-restsharp