预期 C# 使用 Newtonsoft 时未抛出异常

Exception not thrown while expected C# using Newtonsoft

我有一个需要属性的对象

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",
    }
}

这里的Cc 属性是一个空字符串,不是一个List of string。我希望这里有一个例外。 我通过做这样的肮脏事情解决了这个问题:

try
{
    Console.WriteLine(emailStructure.Cc.Count == 0);
}
catch (Exception e)
{
     throw new Exception("Oops something went wrong");
}

有没有更优雅的方式来做到这一点?我为那个解决方案感到羞耻......

Json 数据在抄送字段中包含一个空对象。这导致反序列化列表为空。

如果您希望反序列化在这种情况下抛出异常,则需要更改 Cc 属性 的 JsonProperty 属性,但允许为 null。

[JsonProperty(PropertyName = "Cc", Required = Required.AllowNull)]
public List<string> Cc { get; set; }

这将使反序列化抛出异常。 Json 数据必须包含带有列表的抄送。该列表仍然可以为空,但会反序列化为列表。

例如,这将正确反序列化为 Cc 属性 中的一个空列表:

{
    "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",
    }
}