我正在使用RestSharp RestClient调用SendGrid的Email Activity API,它正在通过标准JSON响应正确返回数据。
但是,我想将其反序列化为C#对象,因为使用它比使用原始JSON字符串要容易得多。因此,我创建了一个C#类,该类具有JSON响应中每个字段的公共属性,并为它们添加了与JSON字段完全相同的名称。
但是当我调用JsonDeserializer()。Deserialize>(response)时,虽然没有错误/异常,但是对象中的所有字段均为NULL。
任何想法有什么问题? (您可以直接删除“ EventType”引用,因为在这里它并不重要)。相关代码如下。
我正在使用RestSharp v106.6.10.0和Newtonsoft.Json v9.0.0.0(后者可能较旧,但这是我们通常使用的库)。项目是.NET v4.6.1
private void QuerySendGridForEmailActivity(EventType eventType)
{
string query = string.Empty;
RestClient client = null;//new RestClient(emailActivityEndpoint);
RestRequest request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Bearer " + apiKey);
request.AddParameter("limit", "1000");
if (eventType == EventType.Opens)
{
// request.AddParameter("query", WebUtility.UrlEncode("(Contains(events,\"open\"))"));
client = new RestClient(emailActivityEndpoint + "?limit=10&query=" + System.Web.HttpUtility.UrlPathEncode("(Contains(events,\"open\"))"));
}
IRestResponse response = client.Execute(request);
if (response != null && response.StatusCode == HttpStatusCode.OK)
{
this.emailActivityEvents = new JsonDeserializer().Deserialize<List<EmailActivityEvent>>(response);
int i = 0;
}
else
{
}
}
public class EmailActivityEvent
{
[DeserializeAs(Name = "from_email")]
public string FromEmail { get;set; }
[DeserializeAs(Name = "msg_id")]
public string MessageId { get; set; }
[DeserializeAs(Name = "subject")]
public string Subject { get; set; }
[DeserializeAs(Name = "to_email")]
public string ToEmail { get; set; }
[DeserializeAs(Name = "status")]
public string Status { get; set; }
[DeserializeAs(Name = "opens_count")]
public int OpensCount { get; set; }
[DeserializeAs(Name = "clicks_count")]
public int ClicksCount { get; set; }
[DeserializeAs(Name = "last_event_time")]
public DateTime LastEventTime { get; set; }
}
[好,我应该早点得到这个,但我认为我不需要这样做。
我必须添加另一个名为“ EmailActivity”的类,该类仅具有电子邮件事件的List <>,并带有反序列化注释,该注释与JSON中项目的实际名称匹配。像这样:
public class EmailActivity
{
[DeserializeAs(Name = "messages")]
public List<EmailActivityEvent> Events { get; set; }
}
然后只需将反序列化调用对此稍作调整:
var emailActivity = new JsonDeserializer().Deserialize<EmailActivity>(response);
然后做到了。 h。
仅供参考,返回的JSON格式如下:
{"messages":
[{
"from_email":"[email protected]",
"msg_id":"msgid",
"subject":"Test",
"to_email":"[email protected]",
"status":"delivered",
"opens_count":0,
"clicks_count":0,
"last_event_time":"2019-11-26T20:30:02Z"
},
{
"from_email":"[email protected]",
"msg_id":"msgid",
"subject":"Test",
"to_email":"[email protected]",
"status":"delivered",
"opens_count":0,
"clicks_count":0,
"last_event_time":"2019-11-26T20:30:01Z"
},
{
"from_email":"[email protected]",
"msg_id":"msgid",
"subject":"Test",
"to_email":"[email protected]",
"status":"delivered",
"opens_count":0,
"clicks_count":0,
"last_event_time":"2019-11-25T22:06:25Z"
}
]}
感谢您的评论!