【发布时间】:2021-09-07 13:57:40
【问题描述】:
我有一个需要属性的对象
public class EmailStructureRequestModel
{
[JsonProperty(PropertyName = "Sender", Required = Required.Always)]
public EmailSender Sender { get; set; }
[JsonProperty(PropertyName = "to", Required = Required.Always)]
public List<string> To { get; set; }
[JsonProperty(PropertyName = "Cc")]
public List<string> Cc { get; set; }
[JsonProperty(PropertyName = "Bcc")]
public List<string> Bcc { get; set; }
[JsonProperty(PropertyName = "Content", Required = Required.Always)]
public EmailContent Content { get; set; }
}
此对象应包含允许发送电子邮件的所有信息。 然后我尝试构建一个 eMailStructure 对象。为此,我使用 Newtonsoft.Json
using (StreamReader r = new StreamReader(filePath))
{
string json = r.ReadToEnd();
EmailStructureRequestModel emailStructure =
JsonConvert.DeserializeObject<EmailStructureRequestModel>(json);
...
}
我的问题是 JsonConvert 没有正确反序列化 Json 字符串。从文件中提取的字符串被正确读取,但是这里的类型不匹配。
{
"Sender": {
"Email": "xxx@xxx.com",
"Password": "pwd",
"Server": "xxxxxx",
"ServerProtocol": "ServerProtocol.ExchangeEWS",
"ServerPort": 993,
"Ssl": true
},
"To" : ["myMail@test.com", ""],
"Cc" : "",
"Bcc" : "",
"Content": {
"EmailObject": "Email test",
"Message": "Hello World",
}
}
这里的抄送属性是一个空字符串,而不是一个字符串列表。我希望这里有一个例外。 我通过做这样的肮脏事情解决了这个问题:
try
{
Console.WriteLine(emailStructure.Cc.Count == 0);
}
catch (Exception e)
{
throw new Exception("Oops something went wrong");
}
有没有更优雅的方式来做到这一点?我为那个解决方案感到羞耻......
【问题讨论】:
-
我还没有尝试过,但是看看文档,
JsonArrayAttribute有帮助吗?
标签: c# json serialization json.net